0

我正在编写一个程序来计算“泰勒级数”,并且得到“inf”作为我的输出。我的程序还没有完成,一切都还没有正常工作,但我希望能够看到我的输出。有没有办法缩短输出或使其可见?谢谢您的帮助。

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

3 回答 3

3

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.

于 2013-03-06T01:58:20.563 回答
2

你的阶乘函数有点古怪。尝试这个:

long factorial( long input ) {
    long output = 1;
    for( long i = 2; i <= input; ++ i ) {
        output *= i;
    }
    return output;
}
于 2013-03-06T02:05:59.817 回答
1

双精度值inf是一个特殊值,用于避免在执行后续数学运算时丢失有关溢出的中间计算的信息。一旦产生了一系列操作inf,它将“粘住”,而不是产生一个错误值的有效数字。

一种常见的获取方法inf是在不是浮点异常的环境中除以零。由于最初x = 1.0 / 0.0 ... (any operations here)的. 您必须找到问题计算并消除它,然后才能看到其余的结果。infinf

于 2013-03-06T01:59:29.797 回答