Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

exp function using c++

Tags:

c++

function

exp

I can't figure out why I keep getting the result 1.#INF from my_exp() when I give it 1 as input. Here is the code:

double factorial(const int k)
{
    int prod = 1;
    for(int i=1; i<=k; i++)
        prod = i * prod;
    return prod;
}

double power(const double base, const int exponent)
{
    double result = 1;
    for(int i=1; i<=exponent; i++)
        result = result * base;
    return result;
}

double my_exp(double x)
{
    double sum = 1 + x;
    for(int k=2; k<50; k++)
        sum = sum + power(x,k) / factorial(k);
    return sum;
}
like image 866
Sean Avatar asked Dec 21 '22 07:12

Sean


2 Answers

You have an integer overflow in your factorial function. This causes it to output zero. 49! is divisible by 2^32, so your factorial function will return zero.

Then you divide by it causing it to go infinity. So the solution is to change prod to double:

double prod = 1;
like image 78
Mysticial Avatar answered Dec 24 '22 03:12

Mysticial


Instead of completely evaluating the power and the factorial terms for each term in your expansion, you should consider how the k'th term is related to the k-1'th term and just update each term based on this relationship. That will avoid the nasty overflows in your power and factorial functions (which you will no longer need). E.g.

double my_exp(double x)
{
    double sum = 1.0 + x;
    double term = x;                 // term for k = 1 is just x
    for (int k = 2; k < 50; k++)
    {
        term = term * x / (double)k; // term[k] = term[k-1] * x / k
        sum = sum + term;
    }
    return sum;
}
like image 32
Paul R Avatar answered Dec 24 '22 01:12

Paul R