Is the following program correct

s=0;
n=input("no of terms");
x=input("put the value of x");
for i=0:n-1
s=(-1).^i*(x.^i)/(factorial(x));
end
disp(s)
;

1 个评论

@Deepak Singh: your code does not add to s, instead your code just returns the result of the last division.
You need to have something like s = s + ...

请先登录,再进行评论。

回答(2 个)

s=0;
n=input("no of terms");
x=input("put the value of x");
for i=0:2:2*(n-1)
s=s+(-1).^(i/2)*(x.^i)/(factorial(i));
end
disp(s)
To avoid overflow in the x^i and factorial(i) terms, it is advisable to code it this way:
n = input("no of terms");
x = input("put the value of x");
summand = 1.0;
summe = 1.0;
for i = 1:n-1
summand = -summand * x/(2*i-1) * x/(2*i);
summe = summe + summand
end

类别

在 帮助中心 和 File Exchange 中查找有关 Programming 的更多信息

产品

回答:

2021-12-18

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by