C ++或C Pow给出错误的结果

c++ or c pow giving wrong result

本文关键字:错误 结果 出错 Pow      更新时间:2023-10-16

>我试图制作自己的 pow,但我得到错误的结果

IM 得到:2^3.3 = 16,这是错误的...为什么?

#include <iostream>
using namespace std;
double new_pow(double base, double power){
double result = 1;
for(int i = 0; i <= power; i++) {
    result *= base;
}

    return result;
}

int main (int argc, char * const argv[]) {
    std::cout << new_pow(2,3.3) << endl;
    return 0;
}

请帮我找到错误

错误是你的循环运行了 4 次,因为 4 次迭代不会超过 3.3。这就是为什么浮点幂是用对数实现的,而不是重复乘法。

伊格纳西奥的回答已经提到了使用对数。但我们最终还是使用了exp()它又是一个库函数。因此,如果您根本不想使用库函数,那么您必须求助于泰勒扩展x^y

正如伊格纳西奥所提到的,对泰勒x^y扩张的直接评估是乏味的,base^power = exp( power*ln(base) )。泰勒对 e^x 的展开非常简单,而对 ln(x( 的展开也非常简单。它们都可用于 C 语言中的简单交互/递归实现

这是使用上述泰勒扩展的e^x的简单实现

double pow_x ( double x , unsigned i )
{
       double prod=1;
       if ( i == 0 )
          return 1;
       while ( i )
       {
             prod*=x;
             i--;
       }
       return prod;
}
             
long long factorial ( unsigned n )
{
     if ( n == 0 )
        return 1;
        
     return n * factorial (n-1);
}
// Function to calculate e^x. Hence expo(5, 20) is calculating
// e^5 by summing 20 terms from the infinite series expansion 
// and NOT a power calculation of 5^20                
double expo ( double x, int terms )
{
       /* terms tells us how long should we expand the taylor's series */
       double sum=0;
       unsigned i=0;
       while ( i< terms )
       {
             sum+= pow_x(x,i)/factorial(i);
             i++;
       }
       return sum;
}

exp(5.93,20)给出了谷歌倾向于同意的376.152869

我希望,使用此示例,您可以自己实现ln(x)

因为你i递增 1。 所以在4.0之后,它会直接递增到5.0,从而使循环的条件检查为假,从而终止循环。

另外,循环变量的起始值是 0 ,所以你应该像这样检查它 -

for(double i=0; i<power; i++)

你可以看看这个答案来了解如何实现浮点幂,并在这里获得相当高级的实现。

for(int i = 0; i <= power; i++)

应该是

for(int i = 1; i <= power; i++)

否则,它将运行一次额外的迭代。

正如伊格纳西奥·巴斯克斯-亚伯兰的回答中提到的。假设你想要功率 y = x^b。这相当于 ln(y( = b*ln(x(。

所以y = exp(b*ln(x))

y = Math.e(b*Math.Log(x)) //Java

通过将power视为int来循环。循环将运行 4 次并返回 2^4 = 16

如何使用对数近似十进制指数。