Sean
Sean

Reputation: 967

exp function using c++

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

Upvotes: 4

Views: 3683

Answers (3)

sara
sara

Reputation: 1

you should just reduce max of k form 50 to like 30 it will work;

and one question your code work just near 0 ?

Upvotes: -2

Paul R
Paul R

Reputation: 212929

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

Upvotes: 6

Mysticial
Mysticial

Reputation: 471219

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;

Upvotes: 7

Related Questions