![](/img/trans.png)
[英]C++ Binary Tree: Return the number of descendants of a node. A leaf has zero. Return -1 if the TreeData is not found
[英]C++: Cosine is wrong, should be zero. 3Pi/2
我有一個程序,我正在嘗試計算cos(M_PI*3/2)
,而不是得到0,因為我應該,我得到-1.83691e-016
我在這里錯過了什么? 我需要的是弧度。
數字M_PI
僅是π的近似值。 你得到的余弦也是一個近似值,它是一個相當不錯的余弦 - 它在小數點后面有十五個正確的數字。
首先,M_PI不是一個非常便攜的宏,並且通常對大約15個小數位有好處,這取決於你使用的編譯器 - 我的猜測是你正在使用微軟的C ++編譯器。
其次,如果您想要更准確(和可移植)的版本,請使用Boost Math庫: http : //www.boost.org/doc/libs/1_55_0/libs/math/doc/html/math_toolkit/tutorial/non_templ。 HTML
第三,正如凱指出的那樣,pi本身就是一個無理數,因此沒有多少比特(或基數10中的數字)就足以准確地表示它。 因此,你實際計算的不是cos(3 * pi / 2),而是“給定所需位的pi的最接近的近似值的3/2的余弦”,這不是3 * pi / 2和因此不會為零。
最后,如果您想要數學常量的自定義精度,請閱讀: http : //www.boost.org/doc/libs/1_55_0/libs/math/doc/html/math_toolkit/tutorial/user_def.html
鑒於double
值的離散性,測試數值相等的標准誤差范圍是numeric_limits<double>::epsilon()
:
#include <iostream>
#include <limits>
#include <cmath>
using namespace std;
int main()
{
double x = cos(M_PI*3/2);
cout << "x = << " << x << endl;
cout << "numeric_limits<double>::epsilon() = "
<< numeric_limits<double>::epsilon() << endl;
cout << "Is x sufficiently close to 0? "
<< (abs(x) < numeric_limits<double>::epsilon() ? "yes" : "no") << endl;
return 0;
}
輸出:
x = << -1.83697e-16
numeric_limits<double>::epsilon() = 2.22045e-16
Is x sufficiently close to 0? yes
如您所見, -1.83697e-16
的絕對值在epsilon 2.22045e-16
給出的誤差范圍內。
Pi是不合理的,計算機無法完美地代表數字。 pi的“正確”值的小誤差導致輸出中的錯誤。 作為1.83691×10 -16關閉還是蠻不錯的。
如果您想了解更多有關實際系統的限制以及輸入中的小錯誤的影響,請參閱http://en.wikipedia.org/wiki/Numerical_stability 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.