Pregunta

I am trying to find e to the power x. Please indicate what could possibly be wrong with my current implementation rather than simply suggesting new/ore efficient solutions (i could find many on the net). There seems to be a logical or run time error, debugging it doesn't show anything. Thanks in advance!

cmath library has been included, program compiles fine..stops on run

double find_e_power_x(int x){
     int i = 1, j = 1, count = 1, accuracy = 15;
     double xd = static_cast<double>(x); //pow takes double args
     double jd = static_cast<double>(j);
     double epx = 1.0;
     while ( count < accuracy ){
           while ( ++i && ++j) {
                 epx += ( pow(xd,jd) / fact(i) ); //static_cast
                 count++;
           }
     }
     return epx;
} 

In response to the comments (pointing out my infinite inner loop),

EDIT:

while ( count < accuracy ){
                 epx += ( pow(xd,jd) / fact(i) ); //static_cast
                 count++;
                 i++;
                 j++;
     }

input =3 answer is incorrect though it does give an output as 3.15485


below is the final version works fine

i/p = 4

o/p = 54.8278

double find_e_power_x(int x){
     int i = 1, count = 1, accuracy = 15;
     double xd = static_cast<double>(x); //pow takes double args
     double id = static_cast<double>(i);
     double epx = 1.0;
     while ( count < accuracy ){
                 epx += ( pow(xd,id) / fact(i) ); //static_cast
                 ++count;
                 ++id;
                 ++i;
     }
     return epx;
} 
¿Fue útil?

Solución

You are incrementing j each time round your loop, but not jd. Therefore your expression:

epx += ( pow(xd,jd) / fact(i) ); //static_cast

is effectively:

epx += ( pow(xd, 1.0) / fact(i) ); //static_cast

each time.

Move this line:

double jd = static_cast<double>(j);

inside your loop or just increment jd directly.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top