[英]C++ Euler Approximation
當我輸入0.1作為步長時,為什么我的代碼僅將x值的輸出提高到2.4? 如果我輸入.01或.001之類的值,則上升到2.5。
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double step;
double x0 = 1.0;
double y0 = 1.0;
double diffY;
std::cout << std::fixed;
std::cout << std::setprecision(2);
cout << "Enter step value: ";
cin >> step;
while (x0 <= 2.5 ) {
diffY = x0 + ((3*y0) / x0);
cout << x0 << " " << y0 << "\n";
x0+=step;
y0+=step*(diffY);
}
return 0; //initially defined the main function to return an int
}
謝謝!
很好的老式浮點數錯誤,以高精度打印x0
,您將得到以下信息:
1.1000000000000001
1.2000000000000002
...
2.4000000000000012
2.5000000000000013
注意如何對你最后的過去,你會增加2.5 過去 ,因此將不會執行你的最后一個循環。 這是因為浮點數是二進制(基數2)而不是十進制(基數10),因此它們不能精確地表示每個數字。 這包括0.1
。
比較浮點數時,應始終使用epsilon:
float eps = step/100; // Only an example.
while (x0 <= 2.5 + eps ) {
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.