我如何使用Bash命令计算pi [英] How can I calculate pi using Bash command
问题描述
我正在学习bash脚本.在探索数学函数时,我遇到了一个计算pi值的命令.
seq -f'4/%g'1 2 99999 |粘贴-sd- + |公元前
尽管我了解基本seq命令的工作原理,但我无法理解上述命令的工作原理.有人可以说明它是如何工作的吗??
这使用Gregory–Leibniz系列计算π的值:
seq -f'4/%g'1 2 99999
生成分数:
4/14/34/54/74/94/114/134/154/174/19
粘贴管道 paste -sd-+
将它们与备用定界符-
和 +
结合在一起.
最后, bc -l </code>执行算术运算以得出结果.
如
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.?
This calculates the value of π using Gregory–Leibniz series:
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:
Using the same expansion for tan-1(x):
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
1 Pi
这篇关于我如何使用Bash命令计算pi的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!