如何在 C# 中计算 PI?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39395/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 09:47:29  来源:igfitidea点击:

How do I calculate PI in C#?

提问by GateKiller

How can I calculate the value of PI using C#?

如何使用 C# 计算 PI 的值?

I was thinking it would be through a recursive function, if so, what would it look like and are there any math equations to back it up?

我在想这将是通过一个递归函数,如果是这样,它会是什么样子,是否有任何数学方程来支持它?

I'm not too fussy about performance, mainly how to go about it from a learning point of view.

我对性能不是太挑剔,主要是从学习的角度如何去做。

采纳答案by wvdschel

If you want recursion:

如果你想要递归:

PI = 2 * (1 + 1/3 * (1 + 2/5 * (1 + 3/7 * (...))))

This would become, after some rewriting:

经过一些重写后,这将变成:

PI = 2 * F(1);

with F(i):

与 F(i):

double F (int i) {
    return 1 + i / (2.0 * i + 1) * F(i + 1);
}

Isaac Newton (you may have heard of him before ;) ) came up with this trick. Note that I left out the end condition, to keep it simple. In real life, you kind of need one.

艾萨克牛顿(你可能以前听说过他;))想出了这个技巧。请注意,我省略了结束条件,以保持简单。在现实生活中,你有点需要一个。

回答by Niyaz

Calculate like this:

像这样计算:

x = 1 - 1/3 + 1/5 - 1/7 + 1/9  (... etc as far as possible.)
PI = x * 4

You have got Pi !!!

你有派!!!

This is the simplest method I know of.

这是我所知道的最简单的方法。

The value of PI slowly converges to the actual value of Pi (3.141592165......). If you iterate more times, the better.

PI 的值慢慢收敛到 Pi 的实际值(3.141592165......)。迭代次数越多越好。

回答by Espo

Here is an article on Calculating PI in C#:

这是一篇关于在 C# 中计算 PI 的文章:

http://www.boyet.com/Articles/PiCalculator.html

http://www.boyet.com/Articles/PiCalculator.html

回答by Skizz

How about using:

如何使用:

double pi = Math.PI;

If you want better precision than that, you will need to use an algorithmic system and the Decimal type.

如果您想要比这更好的精度,则需要使用算法系统和 Decimal 类型。

回答by Anthony Mastrean

In any production scenario, I would compel you to look up the value, to the desired number of decimal points, and store it as a 'const' somewhere your classes can get to it.

在任何生产场景中,我都会强迫您查找该值,以达到所需的小数点数,并将其作为“const”存储在您的类可以访问的地方。

(unless you're writing scientific 'Pi' specific software...)

(除非您正在编写科学的“Pi”特定软件......)

回答by OysterD

Good overview of different algorithms:

不同算法的良好概述:

I'm not sure about the complexity claimed for the Gauss-Legendre-Salamin algorithm in the first link (I'd say O(N log^2(N) log(log(N)))).

我不确定第一个链接中 Gauss-Legendre-Salamin 算法的复杂性(我会说 O(N log^2(N) log(log(N))))。

I do encourage you to try it, though, the convergence is reallyfast.

不过,我确实鼓励您尝试一下,收敛速度非常快。

Also, I'm not really sure about why trying to convert a quite simple procedural algorithm into a recursive one?

另外,我不太确定为什么要尝试将非常简单的程序算法转换为递归算法?

Note that if you are interested in performance, then working at a bounded precision (typically, requiring a 'double', 'float',... output) does not really make sense, as the obvious answer in such a case is just to hardcode the value.

请注意,如果您对性能感兴趣,那么以有界精度(通常需要“双精度”、“浮点”...对值进行硬编码。

回答by DrPizza

public double PI = 22.0 / 7.0;

回答by Anthony Mastrean

Regarding...

关于...

... how to go about it from a learning point of view.

...如何从学习的角度来解决这个问题。

Are you trying to learning to program scientific methods? or to produce production software? I hope the community sees this as a valid question and not a nitpick.

您是否正在尝试学习编程科学方法?或生产生产软件?我希望社区认为这是一个有效的问题,而不是挑剔。

In either case, I think writing your own Pi is a solved problem. Dmitry showed the 'Math.PI' constant already. Attack another problem in the same space! Go for generic Newton approximations or something slick.

无论哪种情况,我都认为编写自己的 Pi 是一个已解决的问题。Dmitry 已经显示了“Math.PI”常数。在同一个空间解决另一个问题!去寻找通用的牛顿近似值或光滑的东西。

回答by joel.neely

Here's a nice approach (from the main Wikipedia entry on pi); it converges much faster than the simple formula discussed above, and is quite amenable to a recursive solution if your intent is to pursue recursion as a learning exercise. (Assuming that you're after the learning experience, I'm not giving any actual code.)

这是一个很好的方法(来自pi 上的主要维基百科条目);它比上面讨论的简单公式收敛得更快,并且如果您打算将递归作为学习练习,那么它非常适合递归解决方案。(假设您追求的是学习体验,我不会提供任何实际代码。)

The underlying formula is the same as above, but this approach averages the partial sums to accelerate the convergence.

基本公式与上面相同,但这种方法会平均部分和以加速收敛。

Define a two parameter function, pie(h, w), such that:

定义一个双参数函数 pie(h, w),使得:

pie(0,1) = 4/1
pie(0,2) = 4/1 - 4/3
pie(0,3) = 4/1 - 4/3 + 4/5
pie(0,4) = 4/1 - 4/3 + 4/5 - 4/7
... and so on

So your first opportunity to explore recursion is to code that "horizontal" computation as the "width" parameter increases (for "height" of zero).

因此,您探索递归的第一个机会是随着“宽度”参数的增加(“高度”为零)对“水平”计算进行编码。

Then add the second dimension with this formula:

然后用这个公式添加第二个维度:

pie(h, w) = (pie(h-1,w) + pie(h-1,w+1)) / 2

which is used, of course, only for values of h greater than zero.

当然,这仅用于 h 大于零的值。

The nice thing about this algorithm is that you can easily mock it up with a spreadsheet to check your code as you explore the results produced by progressively larger parameters. By the time you compute pie(10,10), you'll have an approximate value for pi that's good enough for most engineering purposes.

该算法的好处在于,您可以轻松地使用电子表格对其进行模拟,以便在探索由逐渐增大的参数产生的结果时检查您的代码。到您计算 pie(10,10) 时,您将获得 pi 的近似值,该值足以满足大多数工程目的。

回答by joel.neely

What is PI? The circumference of a circle divided by its diameter.

什么是PI?圆的周长除以其直径。

In computer graphics you can plot/draw a circle with its centre at 0,0 from a initial point x,y, the next point x',y' can be found using a simple formula: x' = x + y / h : y' = y - x' / h

在计算机图形学中,您可以从初始点 x,y 绘制圆心在 0,0 处的圆,可以使用简单的公式找到下一个点 x',y':x' = x + y / h : y' = y - x' / h

h is usually a power of 2 so that the divide can be done easily with a shift (or subtracting from the exponent on a double). h also wants to be the radius r of your circle. An easy start point would be x = r, y = 0, and then to count c the number of steps until x <= 0 to plot a quater of a circle. PI is 4 * c / r or PI is 4 * c / h

h 通常是 2 的幂,因此可以通过移位轻松完成除法(或从双精度数的指数中减去)。h 也想成为圆的半径 r。一个简单的起点是 x = r, y = 0,然后计算 c 的步数,直到 x <= 0 以绘制四分之一圆。PI 是 4 * c / r 或 PI 是 4 * c / h

Recursion to any great depth, is usually impractical for a commercial program, but tail recursion allows an algorithm to be expressed recursively, while implemented as a loop. Recursive search algorithms can sometimes be implemented using a queue rather than the process's stack, the search has to backtrack from a deadend and take another path - these backtrack points can be put in a queue, and multiple processes can un-queue the points and try other paths.

递归到任何深度,对于商业程序来说通常是不切实际的,但尾递归允许算法以递归方式表达,同时实现为循环。递归搜索算法有时可以使用队列而不是进程的堆栈来实现,搜索必须从死角回溯并采取另一条路径 - 这些回溯点可以放入队列中,多个进程可以将这些点取消排队并尝试其他路径。