- I think you want your initialization of nn to be 1, not 0. Otherwise your some is infinite immediately.
- You have an exponentiation in your calculation of ER.
Using a while loop to determine and display the number of terms it takes for a given series to converge within 0.01% of its exact value ((pi^2)/6)?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Bryan Vaughn
am 25 Nov. 2017
Kommentiert: Bryan Vaughn
am 25 Nov. 2017
I'm trying to get a while loop to work to do the above and then display the error and number or iterations ran, but it doesn't seem to be working and I am getting an infinite loop. Any help? My current code is:
ER=100;
s=0;
nn=0;
while (ER >= 0.01)
nn_sum = (1/(nn^2));
s = s + nn_sum; %compute the running sum
ER =(abs(exp((pi^2)/6)-s)/exp((pi^2)/6))*100; %Calculate error
nn = nn + 1; %counter
end
disp(nn-1)
disp(ER)
0 Kommentare
Akzeptierte Antwort
the cyclist
am 25 Nov. 2017
Bearbeitet: the cyclist
am 25 Nov. 2017
Two observations:
If I fix those two things, I get convergence after about 6,000 iterations.
Weitere Antworten (1)
Jose Marques
am 25 Nov. 2017
In the first iteration, seem that nn == 0 and nn_sum == (1/nn^2) which means a zero division. Maybe you can include a if statement to fix this:
ER=100;
s=0;
nn=0;
while (ER >= 0.01)
if (nn ~= 0)
nn_sum = (1/(nn^2));
else
% do something
end
s = s + nn_sum; %compute the running sum
ER =(abs(exp((pi^2)/6)-s)/exp((pi^2)/6))*100; %Calculate error
nn = nn + 1; %counter
end
disp(nn-1)
disp(ER)
0 Kommentare
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!