本文介绍了C ++或C POW给出错误的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作自己的战俘,但结果却是错误的

im trying make my own pow, but i'm getting wrong result

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

im getting : 2^3.3 = 16, which is wrong... why?

#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;
}

请帮助我找到错误

推荐答案

Ignacio的答案已经提到使用对数.但是我们最终还是使用了exp(),它又是一个库函数.因此,如果您根本不想使用库函数,则必须诉诸于泰勒的x^y

Ignacio's answer already mentions using logarithms. But we ultimately end up using exp() which again is a library function. So if you don't want to use library functions at all, then you have to resort to something like Taylor's expansion of x^y

正如伊格纳西奥(Ignacio)所述,base^power = exp( power*ln(base) )是泰勒对x^y展开式的直接评估是乏味的.而且泰勒对e ^ x的扩展非常简单,对于 ln(x)也非常简单.两者都可以在C中简单地进行迭代/递归实现.

As direct evaluation of Taylor's expansion for x^y is tedious, as Ignacio mentioned, base^power = exp( power*ln(base) ). And taylor's expansion for e^x is quite simple and that for ln(x) is also very simple. Both of them yield for simple interative/recursive implementation in C

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

Here is a simple implementation of e^x using the above Taylor's expansion

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);
}

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,其中 Google倾向于同意.

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

I hope, using this example, you can implement ln(x) on your own.

这篇关于C ++或C POW给出错误的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 07:54