Question

I'm writing a program to calculate the 'Taylor Series' and I'm getting 'inf' as my output. I'm not done with the program and everything isn't working properly yet, but I want to be able to see my output. Is there a way to shorten the output or make it visible? Thanks for the help.

#include <iostream>
#include <math.h>
using namespace std;

long double taylorSeries(long double input, int degree);
long int factorial(int input);
long double derivative(long double input);

int main(int argc, const char * argv[])
{

    long double taylorInput = cos(0);    

    cout << taylorSeries(taylorInput, 3) << endl;

    return 0;
}

// taylor series function
long double taylorSeries(long double input, int degree){

    long double i = 0;
    long double accumulation = 0;


    while (i < degree) {
        derivative(input);
        accumulation += (pow(input, i))/factorial(i); 
        i++;
    }

    return accumulation;
}

// function to calculate factorial
long int factorial(int input){

    long int factorial = 0;

    if (input == 1) {
        factorial = 0;
    }

    while (input > 0) {
        if (factorial == 0) {
            factorial = input * (input - 1);
            input -= 2;
        }

        else if (input > 0) {
            factorial *= input;
            input--;
        }


    }
    return factorial;
}

long double derivative(long double input){
     long double derivativeResult = 0;

    derivativeResult = (((input + .001) - (input)) / .001);

    return derivativeResult;
}
Était-ce utile?

La solution

In accumulation += (pow(input, i))/factorial(i); you are dividing by 0.

On the factorial function you are missing the case for 0, factorial of 0 is 1.

EDIT: Factorial of 1 is also not 0, you should take a look at that factorial function first before going forward.

Autres conseils

Your factorial function is a bit screwy. Try this:

long factorial( long input ) {
    long output = 1;
    for( long i = 2; i <= input; ++ i ) {
        output *= i;
    }
    return output;
}

The double value inf is a special value to avoid losing information about an overflowing intermediate calculation when doing a subsequent math operation. Once a chain of operations produces inf it will "stick" rather than producing a valid number that is an incorrect value.

A common way to get inf is to divide by zero in an environment where that's not a floating point exception. So x = 1.0 / 0.0 ... (any operations here) will be inf because of the initial inf. You have to find the problem calculation and eliminate it before you can see the rest of your result.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top