【问题标题】:Why does this not correctly evaluate e^x using the Taylor series?为什么这不能使用泰勒级数正确评估 e^x?
【发布时间】:2019-04-11 12:10:53
【问题描述】:

我正在尝试编写一个名为 expSeries 的函数,它使用另一个函数 factFunc 来评估 e^x。函数factFunc我已经写好了,如下图:

function fact = factFunc(n) 
    f = 1;
    for a = 1:b
        f = f*a;            
    end
    fact = f;
end

我现在正在尝试编写函数 expSeries,它使用泰勒级数评估 e^x。这是我目前所拥有的:

function expo = exponentialFunc(x) 
terms = input('Enter the number of terms');
b = 0;
for i = 1:terms
        b = x/factFunc(terms);
end
expo = b;
end

在主程序中,我有

n = exponentialFunc(4);
disp(n);

在这种情况下,我试图找到 e^4。但是,输出不是预期的。有谁知道我哪里出错了?

【问题讨论】:

    标签: matlab for-loop factorial exponential taylor-series


    【解决方案1】:

    修复factFunc:

    function fact = factFunc(n) 
        f = 1;
        for a = 1:n
            f = f*a;            
        end
        fact = f;
    end
    

    修复到exponentialFunc

    function expo = exponentialFunc(x) 
        terms = input('Enter the number of terms');
        b = 0;
        for i = 0:terms-1
                b = b + x^i/factFunc(i);
        end
        expo = b;
    end
    

    例子

    >> exponentialFunc(4)
    Enter the number of terms10
    
    ans =
    
       54.1541
    

    注意 exp(4) = 54.59815...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-24
      • 2015-07-21
      • 2020-12-12
      • 2014-03-27
      • 2021-12-26
      • 2020-04-01
      • 2013-01-21
      • 1970-01-01
      相关资源
      最近更新 更多