Why my code doesn't work?
이전 댓글 표시
I m trying to make a program that calculates cosh(x) using an approximation. The error between the calculated value and the real value must be less than e-10. If i try to run the code for small numbers or very large the results are correct, but for x=50 for example, the variable termSum becomes NaN and everything is ruined. What am i doing wrong?
clc;
clear;
x = input('Give x to calculate cosh(x): ');
disp(' ')
y1 = (exp(x)+exp(-x))/2;
terms = zeros(1, 1500);
err = 1;
i=0;
while err>10^(-10)
terms(i+1) = (abs(x).^i)/factorial(i);
termSum = sum(terms);
ex = termSum^sign(x);
y2 = (ex + ex^(-1))/2;
err=abs(y2-y1);
i=i+1;
end;
disp(['cosh(', num2str(x),')=', num2str(y2)])
채택된 답변
추가 답변 (1개)
Kelly Kearney
2017년 6월 2일
편집: Kelly Kearney
2017년 6월 2일
I haven't given any thought to the algorithm you show, though a quick test does seem to indicate it converges to cosh for small numbers. But as Guillaume points out, both the numerator and denominator in your terms equation get pretty big pretty quickly:
nterm = 200;
ii = 1:nterm;
x = 50
tnum = abs(x).^ii;
tden = factorial(ii);
terms = tnum./tden;
You can examine the values here:
[tnum' tden' terms']
The denominator becoming infinite (after 172 terms, due to limitations in factorial) isn't actually a problem, although at that point the extra term adds 0 to the sum ( x/Inf = 0 ) and the convergence stops. If the numerator becomes infinite first (e.g. x = 1000), you'll start getting Inf in your terms ( Inf/x = Inf ), and if both become infinite, you'll get NaNs ( Inf/Inf = NaN ).
카테고리
도움말 센터 및 File Exchange에서 Performance and Memory에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!