使用 for 循环计算 Pi
我刚刚编写了一个计算 pi 的程序。然而,即使经过 1000 万次迭代,我的结果还是有点偏差。我得到 3.1415927535897831,而很早就是错误的。它应该是 3.141592653589793238...
所以我的问题是:需要多少次迭代才能获得至少一个准确的答案,一直到 10^-16
这是我的代码,如果任何人都感兴趣:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
long double pi = 4.0;
long double tempPi;
for (int i = 1, j = 3; i <= 10000000; i++, j+=2)
{
tempPi = static_cast<double>(4)/j;
if (i%2 != 0)
{
pi -= tempPi;
}
else if (i%2 == 0)
{
pi += tempPi;
}
}
cout << "Pi has the value of: " << setprecision(16) << fixed << pi << endl;
system("pause");
return 0;
}
任何与性能相关的提示也将不胜感激。
I have just made a program which calculates pi. However, even with 10 million iterations my result is kinda off. I get 3.1415927535897831, whereas already early on is it wrong. It is supposed to be 3.141592653589793238...
So my question is: What is the required amount of iterations to get at least an accurate answer all the way up to 10^-16
Here is my code if anyone is interested:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
long double pi = 4.0;
long double tempPi;
for (int i = 1, j = 3; i <= 10000000; i++, j+=2)
{
tempPi = static_cast<double>(4)/j;
if (i%2 != 0)
{
pi -= tempPi;
}
else if (i%2 == 0)
{
pi += tempPi;
}
}
cout << "Pi has the value of: " << setprecision(16) << fixed << pi << endl;
system("pause");
return 0;
}
Any performance related tips would also be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你使用的是莱布尼兹级数,它的收敛速度非常非常慢。在交替序列(例如您正在使用的序列)中,第一个省略的项可以很好地估计估计中的误差。您的第一个省略项是 4/2000005,因此您应该期望此处的精度少于六位有效数字。
请注意:舍入误差、双精度数字的使用与此处缺乏精度无关。唯一的因素是你使用的是蹩脚的算法。
You are using the Leibniz series, which is very, very slow to converge. In an alternating series such as the one you are using, the first omitted term provides a good estimate of the error in the estimate. Your first omitted term is 4/2000005, so you should expect less than six significant digits of precision here.
Note well: Rounding errors, use of double precision numbers has nothing to do with the lack of precision here. The sole factor is that you are using a crappy algorithm.
有很多方法用于计算 pi。有些收敛速度比其他快。
另请参阅“现代公式”
There are lots of methods for calculating pi. Some converge faster than others.
Also see "Modern Formulae"
问题是
double
并不像您希望的那么准确。您甚至无法以 100% 的精度表示小数 1.2。我没有仔细看代码,看看是否还有其他问题。
The problem is that
double
is not nearly as accurate as you hope. You can't even represent decimal 1.2 with 100% accuracy.I didn't look at the code closely to see if there are other problems.
由于由于舍入误差,经过 1000 万次迭代后结果是错误的,因此循环次数越多,也不会得到正确的答案,只会增加更多的误差。
Since the result is wrong after 10 million iterations due to round-up errors, you won't get the correct answer with more loops, only adding more error.