Why my code doesn't work?
Mostra commenti meno recenti
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)])
Risposta accettata
Più risposte (1)
Kelly Kearney
il 2 Giu 2017
Modificato: Kelly Kearney
il 2 Giu 2017
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 ).
Categorie
Scopri di più su Performance and Memory in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!