我正在开发将用于运动控制的代码,但我遇到了 pow 函数的问题。 我使用 VS2010 作为 IDE。
这是我的问题: 我有:
double p = 100.0000;
double d = 1000.0000;
t1 = pow((p/(8.0000*d),1.00/4.000);
在评估最后一个函数时,我没有得到更好的近似结果。我的 7 位小数是正确的,后面的数字都是垃圾。 我猜 pow 函数只会将任何输入变量转换为 float 并进行计算。
- 我说得对吗?
- 如果是这样,是否有任何代码可以“启发”我重新实现 pow 以获得更高的精度?
编辑:已解决。
毕竟,我遇到了 FPU 配置位的问题,这是由 OGRE 3D 框架使用的 Direct3D 引起的。
如果使用 OGRE,在配置 GUI 上,只需设置“Floating-point mode=Consistent”。
如果使用原始 Direct3D,在调用 CreateDevice 时,确保将“D3DCREATE_FPU_PRESERVE”标志传递给它。
原帖:
You may be using a libray that is changing the default precision of the FPU to single-precision. Then all floating-point operations, even on doubles, will actually be performed as single-precision operations.
As a test, you can try calling _controlfp( _CW_DEFAULT, 0xfffff ); (you need to include ) before performing the calculation to see if you get the correct result. This will reset the floating-point control word to default values. Note that it will reset other settings as well, which may cause issues.
One common library that changes the floating-point precision is Direct3D 9 (and maybe other versions too): By default, it changes the FPU to single-precision when creating a device. If you use it, specify the flag D3DCREATE_FPU_PRESERVE when creating the device to prevent it from changing the FPU precision.
最佳答案
您可能正在使用将 FPU 的默认精度更改为单精度的库。然后是所有的浮点运算,甚至是 double
s, 实际上将作为单精度操作执行。
作为测试,您可以尝试调用 _controlfp( _CW_DEFAULT, 0xfffff );
(您需要包括 <float.h>
)在执行计算之前查看是否得到正确的结果。这会将浮点控制字重置为默认值。请注意,它还会重置其他设置,这可能会导致问题。
Direct3D 9(可能还有其他版本)是一个更改浮点精度的常用库:默认情况下,它会在创 build 备时将 FPU 更改为单精度。如果使用它,请指定标志 D3DCREATE_FPU_PRESERVE
在创 build 备时防止其更改 FPU 精度。
关于c - double 的 Pow 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11524536/