gpt4 book ai didi

c - 被低估的浮点因子

转载 作者:太空宇宙 更新时间:2023-11-04 03:47:43 25 4
gpt4 key购买 nike

大多数物理引擎都支持执行对象轨迹跟踪,该跟踪将返回一个介于 0.0 和 1.0 之间的因子,表示它首先击中对象的对象轨迹的距离。

我担心的问题是,如果将物体移动到其轨迹的该因子会导致其位置超过它应该到达并停止的边界(由于浮点舍入)。

例如,我创建了一个 C 程序,它尝试随机情况直到遇到这个问题,并想出了这个例子(尽管我经历过一些没有那么极端的运动,所以它并不特定于大 float ) :

float start     = 4884361.0f;
float wall = 37961976.0f;
float end = 1398674432.0f;
float time = (wall - start) / (end - start);
float new_pos = start + time * (end - start);
printf("We hit %f, but moving left us at %f.\n", wall, new_pos);

这个案例打印出来:我们命中了 37961976.000000,但是我们移动到 37961980.000000。

所以位置移到了墙的位置之外,现在物体卡在墙内。

有没有办法生成因子或执行因子乘法,使浮点误差始终低于所有可能值的实际值?

最佳答案

计算出的值是下一个(或接近下一个) float 。我们处于 float 精度的极限。为了确保答案位于或偏向预期答案的一侧,有多种方法

1) 更高的中间精度:(应该更频繁地得出正确答案)

float start     = 4884361.0f;
float wall = 37961976.0f;
float end = 1398674432.0f;
double time = ((double)wall - start) / ((double)end - start);
float new_pos = start + time * ((double)end - start);

2) 逻辑:(这绝对有效)

if (new_pos > wall) new_pos = wall;

3) 使用略微较低的时间值:(温和的 hack)

float new_pos = start + nextafterf(time,0.0f) * (end - start);

4) 将 FP 舍入模式更改为向零舍入:(虽然这可能会产生很大影响)

fesetround(FE_TOWARDZERO); 

5) 一个简单的因素:

static const float factor = 0.99999;
float new_pos = start + factor*time * (end - start);

每种方法都有很多优点和缺点。

关于c - 被低估的浮点因子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23020374/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com