计算变量并进行比较

Calculating variables and comparing them

本文关键字:比较 变量 计算      更新时间:2023-10-16

对不起,如果之前有人问过这个问题,但我非常不确定如何制定我的搜索以获得任何相关结果。

基本上我有一个类"Wheel",在该类中,我声明了 == 运算符应该如何工作:

    bool operator == (Wheel& anotherWheel){
    //Circumference of a wheel, times its RPM should give its speed
    //The speed will be in what ever unit the radius is, per minute
    double ourSpeed = 2 * PI * radius * rpm; 
    double anotherSpeed = 2 * PI * anotherWheel.getRadius() * anotherWheel.getRpm();
    cout << ourSpeed << " vs " << anotherSpeed << endl;
    if (ourSpeed == anotherSpeed){
        return true;
    }
    return false;

这有效,除非车轮的半径和 RPM 与其他车轮相同,但切换除外。因此,换句话说,它不会返回 true:

2*PI*3*10 vs 2*PI*10*3

即使我打印出来并且它们在控制台中完全相同(除非我的基本数学知识完全失常,否则它们应该是这样(。

我设法通过在计算速度时添加偏执来解决这个问题:

        double ourSpeed = 2 * PI * (radius * rpm); 
        double anotherSpeed = 2 * PI * (anotherWheel.getRadius() * anotherWheel.getRpm());

但我想了解为什么会发生这种情况,PI 只是我声明的常量双精度,所以这无关紧要。

谢谢!

小心浮点数。

一组浮点数的添加可能会有所不同,具体取决于您添加它们的顺序。乘法和各种其他运算也是如此。

这是因为由于精度限制而发生的舍入。

例如 1/3 + 1/3 = 2/3

然而

0.333333334 + 0.33333334 = 0.6666668而不是 0.66666667,这是理想的 2/3。

您需要使用容差级别来确定该值是否"足够接近"以被视为相等。

一个非常基本(幼稚和不灵活(的选项是这样的:

if(fabs(a - b) < 0.001)

但是有更好的方法。

如果你真的想了解浮点数,从这里开始:Oracle 浮点数 - 它会告诉你你需要知道的一切,除此之外还有更多。