The Computer Oracle

How can I generate Pi to a given number of decimal places from a script?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Techno Intrigue Looping

--

Chapters
00:00 How Can I Generate Pi To A Given Number Of Decimal Places From A Script?
00:19 Accepted Answer Score 19
01:58 Thank you

--

Full question
https://superuser.com/questions/275516/h...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#commandline #unix #script

#avk47



ACCEPTED ANSWER

Score 19


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:

#!/bin/bash
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.