c++ - 为什么从 C++11 中删除了 std::pow(double, int)?

标签 c++ c++11 c++-standard-library

在查看 Efficient way to compute p^q (exponentiation), where q is an integer 时并查看 C++98 和 C++11 标准,我注意到显然 std::pow(double, int) 重载已在 C++11 中删除。

在 C++98 26.5/6 中,它具有 double pow(double, int); 签名。

在 C++11 26.8 中,我只能找到采用一对 floatdoublelong double 的重载,以及明确注意,如果参数类型为 integer&double 的混合,则应选择 pow(double, double) 重载。

这只是对先前意图的澄清,它们是在 C++98 中错误添加的,是在 C++11 中实际删除的,还是其他什么?

显然 pow(double, int) 版本提供了一个很好的优化机会,因此将它们删除似乎很奇怪。编译器仍然是符合提供这种优化重载的标准吗?

最佳答案

double pow(double, int);

尚未从规范中删除。它只是被改写了。它现在位于 [c.math]/p11 中。它的计算方式是一个实现细节。唯一改变的 C++03 签名是:

float pow(float, int);

现在返回 double :

double pow(float, int);

并且更改是为了 C 兼容性。

澄清:

26.8 [cmath]/p11 说:

Moreover, there shall be additional overloads sufficient to ensure:

  1. If any argument corresponding to a double parameter has type long double, then all arguments corresponding to double parameters are effectively cast to long double.

  2. Otherwise, if any argument corresponding to a double parameter has type double or an integer type, then all arguments corresponding to double parameters are effectively cast to double.

  3. Otherwise, all arguments corresponding to double parameters are effectively cast to float.

这一段暗示了大量的重载,包括:

double pow(double, int);
double pow(double, unsigned);
double pow(double, unsigned long long);

等等

这些可能是实际的重载,也可能是使用受限模板实现的。我个人以两种方式实现了它,并且强烈支持受限模板实现。

第二次更新以解决优化问题:

允许实现优化任何重载。但请记住,优化应该是。优化后的版本应该返回相同的答案。从 pow 等函数的实现者那里获得的经验是,当您遇到麻烦以确保采用积分指数的实现给出与采用浮点指数的实现相同的答案时,“优化”通常会变慢。

作为演示,以下程序打印出 pow(.1, 20) 两次,一次使用 std::pow,第二次使用利用积分指数的“优化”算法:

#include <cmath>
#include <iostream>
#include <iomanip>

int main()
{
    std::cout << std::setprecision(17) << std::pow(.1, 20) << '\n';
    double x = .1;
    double x2 = x * x;
    double x4 = x2 * x2;
    double x8 = x4 * x4;
    double x16 = x8 * x8;
    double x20 = x16 * x4;
    std::cout << x20 << '\n';
}

在我的系统上打印出来:

1.0000000000000011e-20
1.0000000000000022e-20

或以十六进制表示:

0x1.79ca10c92422bp-67
0x1.79ca10c924232p-67

是的,pow 的实现者确实担心低端的所有这些位。

因此,虽然可以自由地将 pow(double, int) 改组为单独的算法,但我知道的大多数实现者已经放弃了该策略,可能除了检查对于非常小的积分指数。在这种情况下,使用浮点指数将该检查放入实现中通常是有利的,以便为您的优化带来最大的 yield 。

关于c++ - 为什么从 C++11 中删除了 std::pow(double, int)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5627030/

相关文章:

c++ - gdb vector 尝试获取不在内存中的地址

c++ - 如何进行逐元素比较并根据结果做不同的操作

opencv - C++将两个共享库链接到main.cpp

c++ - std::variant 转换构造函数不处理 const volatile 限定符

c++ - 系统 ("history") 不工作

c++ - 创建 shared_ptr 到堆栈对象

c++将数据源函数作为参数传递

c++ - 使用 std::vector< std::shared_ptr<const T>> 是反模式吗?

c++ - 为什么 cout.precision() 会影响整个流?

c++ - 带参数包的 std::min