Approximating Euler's sum using while loop
Ältere Kommentare anzeigen
So I have been working on this code that will approximate the Euler's approximation to within .01% of the actual value. It seems that I may be missing something, when the function runs it will only print the 3 terms, and will print .36111--- for almost any number. The actual value that I am trying to approximate is pi^2/6. Could anybody take a look at what I am missing
function ApproxEulers(PercError,exact)
i=1;
sum=0;
Error = 100;
while Error >= PercError ;
i=i+1;
sum = sum + (1/(i^2));
Error = Error -(100*abs((exact - sum)/exact));
end
fprintf('The number of terms: %d \n', i)
fprintf('The approxamite value: %.8f \n', sum)
fprintf('The exact value: %.8f \n', exact)
end
Akzeptierte Antwort
Weitere Antworten (1)
Eric
am 10 Nov. 2014
0 Stimmen
2 Kommentare
Orion
am 10 Nov. 2014
The initialization depends on "where" you will increase your variable.
Here, at the first iteration, i becomes 1, which will give you the first element of your sum.
1/1² + 1/2² + ...
in your original code, you were calculating :
1/2² + 1/3² + ... => miss 1, you were calculating "pi^2/6 - 1"
you can change the initialization to 1, but then the increase of i must be at the end of the while loop instead of the beginning.
Eric
am 11 Nov. 2014
Kategorien
Mehr zu Programming finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!