【问题标题】:C++ Euler ApproximationC++ 欧拉近似
【发布时间】:2017-02-19 11:52:51
【问题描述】:

为什么当我输入 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
} 

谢谢!

【问题讨论】:

  • 您应该使用基于整数的限制进行循环,并在循环内按比例缩小值。否则,您的循环可能会运行不同的次数,具体取决于编译器、编译器选项等。

标签: c++ approximation


【解决方案1】:

很好的老式浮点数错误,以高精度打印出你的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 ) {
    ...

欲了解更多信息,read this。想玩的话here is a live example.

【讨论】:

  • “这是因为浮点数是二进制(以 2 为底)而不是十进制(以 10 为底),因此它们不能准确地表示每个数字。” 这适用于任何整数基 (给定有限多个数字)。
  • 我建议不要使用浮点循环计数器进行循环。不择手段,将这些循环约束值设为整数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-17
  • 1970-01-01
相关资源
最近更新 更多