Function for calculating Pi using taylor series in c++
所以我对我的代码不起作用的原因一无所知,本质上,我编写的函数使用泰勒级数来计算π的估计值,只要我运行程序,它就会崩溃。
这是我的密码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | #include <iostream> #include <math.h> #include <stdlib.h> using namespace std; double get_pi(double accuracy) { double estimate_of_pi, latest_term, estimated_error; int sign = -1; int n; estimate_of_pi = 0; n = 0; do { sign = -sign; estimated_error = 4 * abs(1.0 / (2*n + 1.0)); //equation for error latest_term = 4 * (1.0 *(2.0 * n + 1.0)); //calculation for latest term in series estimate_of_pi = estimate_of_pi + latest_term; //adding latest term to estimate of pi n = n + 1; //changing value of n for next run of the loop } while(abs(latest_term)< estimated_error); return get_pi(accuracy); } int main() { cout << get_pi(100); } |
代码背后的逻辑如下:
谢谢你的帮助
您的函数中有几个错误。查看我的注释,行以"//note:"开头。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | double get_pi(double accuracy) { double estimate_of_pi, latest_term, estimated_error; int sign = -1; int n; estimate_of_pi = 0; n = 0; do { sign = -sign; //NOTE: This is an unnecessary line. estimated_error = 4 * abs(1.0 / (2*n + 1.0)); //equation for error //NOTE: You have encoded the formula incorrectly. // The RHS needs to be "sign*4 * (1.0 /(2.0 * n + 1.0))" // ^^^^ ^ latest_term = 4 * (1.0 *(2.0 * n + 1.0)); //calculation for latest term in series estimate_of_pi = estimate_of_pi + latest_term; //adding latest term to estimate of pi n = n + 1; //changing value of n for next run of the loop } //NOTE: The comparison is wrong. // The conditional needs to be"fabs(latest_term) > estimated_error" // ^^^^ ^^^ while(abs(latest_term)< estimated_error); //NOTE: You are calling the function again. // This leads to infinite recursion. // It needs to be "return estimate_of_pi;" return get_pi(accuracy); } |
另外,
1 | get_pi(0.001) |
如果项的绝对值小于0.001,则函数可以返回。
这是一个适用于我的函数的更新版本。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | double get_pi(double accuracy) { double estimate_of_pi, latest_term; int sign = -1; int n; estimate_of_pi = 0; n = 0; do { sign = -sign; latest_term = sign * 4 * (1.0 /(2.0 * n + 1.0)); //calculation for latest term in series estimate_of_pi += latest_term; //adding latest term to estimate of pi ++n; //changing value of n for next run of the loop } while(fabs(latest_term) > accuracy); return estimate_of_pi; } |
你的休息条件可以改写为
1 | 2*n + 1 < 1/(2*n + 1) => (2*n + 1)^2 < 1 |
对于任何阳性的
1 | return estimated_error; |
您当前正在无结束地递归调用函数(假设您修复了停止条件)。
此外,您还有一个
我对这种迭代的建议是总是在一些最大的迭代次数上中断。在这种情况下,你知道它是收敛的(假设你修正了数学),但一般来说,你永远不能确定你的迭代是收敛的。
你的报税表可能就是原因。
试着返回"估计值",而不是得到"精确值"。