My thoughts on Slackware, life and everything

Calculating PI

The Internet is full of “one-liners” and if you search a bit, you can find many. A one-liner typically means (a chain of) commands that produce useful results quickly.

I came across a nice one-liner just now. The “binary calculator” or bc is a powerful UNIX tool. Calculating the value of PI with an arbitrary number of decimals (the number of decimals only restricted by the power of your OS, available RAM or internal limitations of the program) goes like this:

echo “scale=XXXX;4*a(1)” | bc -l

Where “XXXX” is the number of digits you want to calculate. Calling bc with the “-l” parameter causes bc to load it’s mathematical library. The function “a()” is the arctangent function.

Let’s say you need the value of PI with an accuracy of a thousand decimals.

$ echo "scale=1000;4*a(1)" | bc -l
3.141592653589793238462643383279502884197169399375105820974944592307\
81640628620899862803482534211706798214808651328230664709384460955058\
22317253594081284811174502841027019385211055596446229489549303819644\
28810975665933446128475648233786783165271201909145648566923460348610\
45432664821339360726024914127372458700660631558817488152092096282925\
40917153643678925903600113305305488204665213841469519415116094330572\
70365759591953092186117381932611793105118548074462379962749567351885\
75272489122793818301194912983367336244065664308602139494639522473719\
07021798609437027705392171762931767523846748184676694051320005681271\
45263560827785771342757789609173637178721468440901224953430146549585\
37105079227968925892354201995611212902196086403441815981362977477130\
99605187072113499999983729780499510597317328160963185950244594553469\
08302642522308253344685035261931188171010003137838752886587533208381\
42061717766914730359825349042875546873115956286388235378759375195778\
18577805321712268066130019278766111959092164201988

Isn’t this fun? And on my old dual P2/233MHz server, this took roughly eight seconds.

Now, to compare the usefulness of the Linux platform to good old Solaris, this is what you get on Solaris 8:

$ echo "scale=1000;4*a(1)" | bc -l
scale factor is too large
3.14159265358979323844

Cheers, Eric

3 Comments

  1. Fish_Kungfu

    Very cool! Thanks for posting that fun gnugget! Using that as inspiration, here is a way to calculate Phi, or the Golden Ratio (http://en.wikipedia.org/wiki/Golden_ratio), to an arbitrary number of decimal places. The example below calculates to 10 decimal places.

    echo “scale=10;(1 + sqrt(5))/2” | bc -l

    Slack On!
    ~~Fish~~

  2. Ron

    I ran 6 simultaneous instances to determine if I had a solid overclock in Linux. Thanks!

  3. Aristotle Pagaltzis

    Less typing:

    bc -l <<< 'scale=1000; 4*a(1)'

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

© 2024 Alien Pastures

Theme by Anders NorenUp ↑