Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I calculate pi using Bash command

Tags:

bash

shell

seq

bc

I am learning bash scripting. While exploring the math functions i am came across a command which calculated the value of pi.

seq -f '4/%g' 1 2 99999 | paste -sd-+ | bc -l

Although i understand how the basic seq command works, I am unable to understand how does the above command works. Can anybody please clarify how does it work.?

like image 756
poorvank Avatar asked May 07 '14 17:05

poorvank


People also ask

How do I get pi in bash?

a is arctan, and this give pi to 1000 digits. You could pipe sed 's/. $//' at the end and change it to scale=1001 because the last digit gets fudged but I still like this answer.

What is P in bash command?

command command in bash: Run command with arguments ignoring any shell function named command. The '-p' option means to use a default value for $PATH that is guaranteed to find all of the standard utilities.


1 Answers

This calculates the value of π using Gregory–Leibniz series:

enter image description here

seq -f '4/%g' 1 2 99999 generates the fractions:

4/1
4/3
4/5
4/7
4/9
4/11
4/13
4/15
4/17
4/19

The paste pipeline paste -sd-+ combines those with alternate delimiters - and +.

Finally, bc -l performs the arithmetic to give the result.


EDIT: As noted in the comment, this sequence converges very slowly. Machin's formula has a significantly higher rate of convergence:

enter image description here

Using the same expansion for tan-1(x):

enter image description here

to compute π, we can see that it produces the correct value to 50 digits1 using just the first 50 terms of the series:

$ { echo -n "scale=50;"; seq 1 2 100 | xargs -n1 -I{} echo '(16*(1/5)^{}/{}-4*(1/239)^{}/{})';} | paste -sd-+ | bc -l
3.14159265358979323846264338327950288419716939937510

With just 100 terms, the value of π is computed accurately to more than 100 digits:

$ { echo -n "scale=100;"; seq 1 2 200 | xargs -n1 -I{} echo '(16*(1/5)^{}/{}-4*(1/239)^{}/{})';} | paste -sd-+ | bc -l
3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679

1Pi

like image 151
devnull Avatar answered Sep 22 '22 08:09

devnull