【问题标题】:What is the difference between pow and powfpow 和 pow 和有什么不一样
【发布时间】:2019-04-04 04:42:52
【问题描述】:

我尝试解决一个数学问题,但我的输出灵敏​​度略有不同,例如 0.07。然后我比较了代码中的pow()powf(),我看到了这种敏感性。代码如下:

int main()
{

    int terms, sign=-1;
    double x, operation=0.0;

    printf("Please enter the number of terms : ");
    scanf_s("%d", &terms);

    while (terms <= 0)
    {
        printf("Please re-enter the number of terms :");
        scanf_s("%d", &terms);
    }

    printf("Please enter a value for x :");
    scanf_s("%lf", &x);

    for (int i = 1; i <= terms; i++)
    {
    sign = sign * (-1);
    operation = operation + sign * powf(x + i / 10.0, (2 * i) - 1) / (2 * i);
    }
    printf("The result is : %.2lf\n", operation);

    system("pause");
    return 0;

}

示例:

terms  : 10

x : 1.1

output  : `-59783.61` with `powf`

output  : `-59783.67` with `pow`

这两个函数有什么区别?

【问题讨论】:

  • man pow: double pow(double x, double y)float powf(float x, float y)
  • 无关:请不要使用 _s 函数,它们并不比便携式对应物更安全。
  • 与其考虑 0.07 的差异,不如考虑 1,000,000 中 1 部分的差异 - 大约是典型 float 的精度。
  • .1.1f之间。

标签: c floating-accuracy


【解决方案1】:

powdoubles 上运行。 powffloats 上运行。这是 C 中相当标准的表示法,其中函数的基本名称将用于默认类型的操作数(和返回值)(如 intdouble),而前缀和后缀版本用于其他类型(如longfloat 等)。这是一个参考:http://pubs.opengroup.org/onlinepubs/9699919799/

这种数据类型的差异完全解释了您在结果中看到的差异。

doubles 在尾数中包含 53 位精度,可转换为大约 16 位十进制精度。这超出了您显示结果的精度,因此对于您的目的来说可能足够准确。

另一方面,floats 在尾数中只有 24 位,这意味着大约 7 个十进制数字。任何操作组合都会导致舍入误差几乎立即蔓延到您的显示精度范围内。

【讨论】:

    【解决方案2】:

    C 语言在 C11 之前没有“泛型函数”。相反,标准库中有不同的函数用于不同的数据类型。

    &lt;math.h&gt;*f 函数对单精度浮点数进行操作(floats 在内部使用单精度。double 代表 ... 双精度。始终使用非 f 函数对于双参数。

    【讨论】:

      【解决方案3】:

      区别在于:

      float powf( float base, float exponent );
      double pow( double base, double exponent );
      

      描述in here

      pow 函数计算 base 的幂 exponent

      【讨论】:

      • 你引用了什么来源?
      • 谢谢。这确实是一个必要的改进。注明您的来源非常重要,尤其是当您进行这样的直接引用时。
      【解决方案4】:

      正如 here 所说,pow 采用 double,而 powf 采用 float 使其精度大大降低。

      【讨论】:

        【解决方案5】:

        powf 返回并接受 float 的参数。

        pow 返回 double 并接受 double 的参数。如果给定浮点数作为参数,则通过通常的提升规则将其转换为doubleSee here

        您在结果中看到的差异是由于double 的精度更高

        【讨论】:

          猜你喜欢
          • 2011-07-07
          • 2021-08-26
          • 1970-01-01
          • 1970-01-01
          • 2013-05-22
          • 1970-01-01
          • 1970-01-01
          • 2017-04-25
          • 1970-01-01
          相关资源
          最近更新 更多