类似浮点函数的结果不同 [英] Different results from similar floating-point functions

查看:44
本文介绍了类似浮点函数的结果不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有2个功能应该做同样的事情

so i have 2 functions that should do the same thing

float ver1(float a0, float a1) {
    float r0 = a0 - a1;
    if (abs(r0) > PI) {
        if (r0 > 0) {
            r0 -= PI2;
        } else {
            r0 += PI2;
            }
    }
    return r0;
}

float ver2(float a0, float a1) {
    float a2 = a1 - PI2;

    float r0 = a0 - a1;
    float r1 = a0 - a2;

    if (abs(r0) < abs(r1)) {
        return r0;
    }
    if (abs(r0) > abs(r1)) {
        return r1;
    }

    return 0;
}

注意:PI和PI2是pi和2 * pi的浮点常量

note: PI and PI2 are float constants of pi and 2*pi

奇怪的是,有时它们会产生不同的结果,例如,如果将它们喂入0.28605145和5.9433694,则第一个结果为0.62586737,第二个结果为0.62586755,我不知道是什么原因造成的.

The odd thing is that sometimes they produce different results, for example if you feed them 0.28605145 and 5.9433694 then the first one results in 0.62586737 and the second one in 0.62586755 and i cant figure out whats causing this.

如果您手动计算结果应该是什么,您会发现第二个答案是正确的.我在2d物理模拟中使用了此功能,真正奇怪的是,第一个答案(错误的答案)在那里起作用,而第二个答案(正确的答案)使其表现出各种疯狂的效果.与未知来源的差异如此之小,影响如此深远:|

If you manually calculate what the result should be you'll find that the second answer is correct. This function i use in a 2d physical sim and the really odd thing is that the first answer (the wrong one) works there while the second one (the right one) makes it act all kinds of crazy. Such a tiny difference from an unknown source and such a profound effect :|

在这一点上我还是会转换为矩阵,但是这种奇怪的情况让我感到好奇,有人知道发生了什么吗?

At this point im switchign to matrices anyway but this odd situation got me curious, anybody know whats going on?

推荐答案

float通常具有大约24位的精度,或大约7个小数位.

float typically has a precision of about 24 bits, or about 7 decimal places.

您要减去两个相似幅度的数字(第一个是r0+PI2,第二个是a1-PI2),因此也遇到了重要度损失-其中的几个最高有效位结果为零,因此剩下的位数更少.这就是为什么答案仅匹配约6个小数位的原因.

You are subtracting two numbers of similar magnitude (r0+PI2 in the first, a1-PI2 in the second), and so are experiencing loss of significance - several of the most significant bits of the result are zero, so there are fewer bits left to represent the difference. That is why the answers match to only about 6 decimal places.

如果需要更高的精度,则double或32位或更大的定点表示形式可能比float更合​​适.还提供了任意精度的库,例如 GMP ,尽管可以算术,但它们可以表示具有所需的所有精度的数字.会比内置类型慢得多.

If you need more precision, then a double or a 32-bit or larger fixed-point representation might be more suitable than a float. There are also arbitrary-precision libraries available, such as GMP, which can represent numbers with all the precision you need, although arithmetic will be significantly slower than with built-in types.

这篇关于类似浮点函数的结果不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆