Does anybody have a script that I could easily run like:

sh generatepi.sh 10000

where 10000 is the number of generated π (Pi) decimal places.


Assuming you have the bc (Basic Calculator) utility on your system, you could use the following command and a bit of good old mathematics to calculate π to 10,000 decimal places:

echo "scale=10000; 4*a(1)" | bc -l

This will probably take quite a while to complete for 10,000 decimal places.

Breaking the command down...

  • scale=10000 - this specifies the number of decimal places to use for the result
  • 4*a(1) - this returns the arctangent of 1 [which equals 45°: 45 x (π/180), or ¼π] then multiplies by 4 to get π.
  • bc -l - pipe the complete function string into the bc utility, -l specifies to load the standard math library that's needed for the arctangent function, a().

To wrap this in a script as you specify in your question, use your favourite editor to write the following and save it as generatepi.sh:

echo "scale=$1; 4*a(1)" | bc -l

Then from a terminal use chmod +x generatepi.sh from the folder you saved the file to, which will give the script execution rights. The syntax is then generatepi.sh [number of places]. Note this uses a very basic way of handling parameters and wouldn't validate the input, so make sure you only pass it positive integers as a parameter.

Most Linux systems should have bc but you may need to install it in some cases (e.g. apt-get on Ubuntu, emerge on Gentoo etc). There is also a port of bc for Windows.

  • there's native pi calculators for windows - overclockers use them for stability testing – Journeyman Geek Apr 26 '11 at 13:22
  • ~3min on my machine, pretty useless in a script. +1 though for using bc. – cYrus Apr 26 '11 at 13:45
  • I think the "b" in "bc" stands for "Berkeley" rather than "Bench". – user1364368 Apr 20 '17 at 10:24
  • Thanks. Updated to 'basic calculator' based on en.wikipedia.org/wiki/Bc_(programming_language) – Gaff Apr 20 '17 at 15:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.