c - double 的 Pow 实现

标签 c floating-point direct3d ogre3d fpu

我正在开发将用于运动控制的代码,但我遇到了 pow 函数的问题。 我使用 VS2010 作为 IDE。

这是我的问题: 我有:

    double p = 100.0000;
    double d = 1000.0000;
    t1 = pow((p/(8.0000*d),1.00/4.000);

在评估最后一个函数时,我没有得到更好的近似结果。我的 7 位小数是正确的,后面的数字都是垃圾。 我猜 pow 函数只会将任何输入变量转换为 float 并进行计算。

  1. 我说得对吗?
  2. 如果是这样,是否有任何代码可以“启发”我重新实现 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/

相关文章:

c - 在帕特里夏/基数树上插入单词时遇到问题

c - 将文本文件读入数组

c - 如何使用 fread() 循环读取整个文件?

c - POSIX 消息队列,errno 90,消息太长

c++ - DirectXMath vector 运算精度

direct3d - 试图找到 HLSL 编译器

PHP 从数据库返回 float 而不是字符串?

c - 是否总是可以将 `int` 转换为 `float`

functional-programming - 方案:仅使用 R6RS,如何确定浮数的尾数和指数

windows - 将全屏 XNA 游戏放在首位