c++ - cmath 中的 pow() 实现和高效替换

标签 c++ c math cmath

<分区>

我读过 cmath 通过执行 exp(b*log(a)) 计算 pow(a,b)。当 b 是整数时不应使用它,因为它会大大减慢计算速度。当

  1. 计算很多具有相同常量a的连续pow()
  2. 预先知道b肯定是一个整数?

我正在寻找在这些特定情况下高效的快速替代方案。

最佳答案

多年来我收集了许多更快的替代方案,它们通常依赖于函数的递归实现,并在必要时通过位移来处理乘法。以下提供为 integerfloatdouble 定制的函数。它们带有正常的 disclaimer: 虽然速度更快,但并非所有可能的测试都已运行,用户应在调用之前和返回时验证输入是否正常......等等,等等,等等......但是,他们是非常有用:

我相信适当的归因于 Geeks for Geeks Pow(x,n)正如蓝月亮所指出的那样。我早就失去了链接.. 看起来像他们。 (减去一两次调整)。

/* Function to calculate x raised to the power y

    Time Complexity: O(n)
    Space Complexity: O(1)
    Algorithmic Paradigm: Divide and conquer.
*/
int power1 (int x, unsigned int y)
{
    if (y == 0)
        return 1;
    else if ((y % 2) == 0)
        return power1 (x, y / 2) * power1 (x, y / 2);
    else
        return x * power1 (x, y / 2) * power1 (x, y / 2);

}

/* Function to calculate x raised to the power y in O(logn)
    Time Complexity of optimized solution: O(logn)
*/
int power2 (int x, unsigned int y)
{
    int temp;
    if (y == 0)
        return 1;

    temp = power2 (x, y / 2);
    if ((y % 2) == 0)
        return temp * temp;
    else
        return x * temp * temp;
}

/* Extended version of power function that can work
for float x and negative y
*/
float powerf (float x, int y)
{
    float temp;
    if (y == 0)
    return 1;
    temp = powerf (x, y / 2);
    if ((y % 2) == 0) {
        return temp * temp;
    } else {
        if (y > 0)
            return x * temp * temp;
        else
            return (temp * temp) / x;
    }
}

/* Extended version of power function that can work
for double x and negative y
*/
double powerd (double x, int y)
{
    double temp;
    if (y == 0)
    return 1;
    temp = powerd (x, y / 2);
    if ((y % 2) == 0) {
        return temp * temp;
    } else {
        if (y > 0)
            return x * temp * temp;
        else
            return (temp * temp) / x;
    }
}

关于c++ - cmath 中的 pow() 实现和高效替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26860574/

相关文章:

php - 给定每个矩形的左上角(x0,y0)和右下角(x1,y1)的数学/算法/JS : How to determine if 2+ rectangles intersect,

c++ - JPEG of Death 漏洞如何运作?

c++ - 为什么 Qt 告诉我 : expected class name?

c - 如何解决vfmadd213ps的 "illegal instruction"?

c - 从 main 返回 errno

为用户空间和内核空间编译相同的 C 代码

c# - Parallel.For 有异常行为

c++ - 在实现文件中添加成员函数

c++ - 有没有办法将 Fitnesse 合并到 C++ 代码中?

python - 用于确定两个数字在舍入到 n 个有效十进制数字时是否几乎相等的函数