我正在尝试编写一个名为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。但是,输出不是预期的。有谁知道我要去哪里错了?
答案 0 :(得分:3)
固定为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 ...