如何缩短我的输出?目前正在'inf'

How to shorten my output? Currently getting 'inf'

本文关键字:inf 目前 何缩短 我的 输出      更新时间:2023-10-16

我正在写一个程序来计算'泰勒级数',我得到'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;
}

accumulation += (pow(input, i))/factorial(i);中,您将除以0。

在阶乘函数中你忽略了0的情况,0的阶乘是1

编辑:1的阶乘也不是0,在继续之前,您应该先看看这个阶乘函数

您的阶乘函数有点奇怪。试试这个:

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

双值inf是一个特殊值,用于避免在执行后续数学操作时丢失有关溢出中间计算的信息。一旦操作链产生inf,它将"粘",而不是产生一个有效的数字,这是一个不正确的值。

获得inf的一种常见方法是在非浮点异常的环境中除以零。所以x = 1.0 / 0.0 ... (any operations here)会变成inf因为初始的inf。你必须找到问题计算并消除它,然后才能看到剩下的结果。