[英]C++ truncation error?
我正在學習C ++,並在嘗試使用公式來計算電流時遇到了這個問題。
我得到: 0.628818
答案應該是:
f = 200赫茲
R = 15歐姆
C = 0.0001(100µF)
L = 0.01476(14.76mH)
E = 15伏
答案:I = 0.816918A(計算得出)
下面是我的代碼:
#include <iostream>
#include <cmath>
int main()
{
const double PI = 3.14159;
double r = 15;
double f = 200;
double c = 0.0001;
double l = 0.01476;
double e = 15;
double ans = e / std::sqrt(std::pow(r, 2) + (std::pow(2 * PI*f*l - (1.0 / 2.0 * PI*f*c), 2)));
std::cout << "I = " << ans << "A" << std::endl;
}
我已經閱讀了有關截斷錯誤的信息,並嘗試使用1.0 / 2.0,但似乎也不起作用。
截斷誤差是指僅使用無限序列的前N個項來估計值。 因此,您的問題的答案是“否”。 您可能會發現以下內容值得關注...。
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
template<typename T>
T fsqr(T x) { return x * x; }
// Numerically stable and non-blowuppy way to calculate
// sqrt(a*a+b*b)
template<typename T>
T pythag(T a, T b) {
T absA = fabs(a);
T absB = fabs(b);
if (absA > absB)
{
return absA*sqrt(1.0 + fsqr(absB / absA));
} else if (0 == absB) {
return 0;
} else {
return absB*sqrt(1.0 + fsqr(absA / absB));
}
}
int main () {
double e, r, f, l, c, ans;
const double PI = 3.14159265358972384626433832795028841971693993751058209749445923078164062862089986280348253421170;
cout << "Insert value for resistance: " << endl;
cin >> r ;
cout << "Insert value for frequency: " << endl;
cin >> f;
cout << "Insert value for capacitance: " << endl;
cin >> c;
cout << "Insert value for inductance: " << endl;
cin >> l;
cout << "Insert value for electromotive force (voltage): " << endl;
cin >> e;
ans = e / pythag(r, 2*PI*f*l - (1/(2*PI*f*c)) );
cout << "I = " << ans << "A" << endl;
system("pause");
return 0;
}
只是開個玩笑。
主要問題是用πfC乘以½而不是除以,這里:
(1.0 / 2.0 * PI*f*c)
最好使用適當的命名值來避免此類問題(這也使您可以使用更快更精確的x*x
代替std::pow(x,2)
)。
您還可以通過使用標准斜邊函數來代替其中的一些算法,而不是內聯方根和平方根:
double ans = e / std::hypot(r, (2*PI*f*l - 0.5/PI/f/c));
#include <iostream>
#include <cmath>
int main()
{
static constexpr double PI = 4 * std::atan(1);
double r = 15; // ohm
double f = 200; // hertz
double c = 0.0001; // farad
double l = 0.01476; // henry
double e = 15; // volt
double current = e / std::hypot(r, (2 * PI*f*l - 0.5/PI/f/c));
std::cout << "I = " << current << "A" << std::endl;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.