Estimating the value of pi using a summation through creation of an m.file by using a loop.
Ältere Kommentare anzeigen
My script is missing something. Perhaps I do not understand the meaning of 'while' or 'for' correctly. But here is my code:
{% this script approximates the value of pi
n=0;
x=0;
while n<100000 % loop ends at 10^6
n=n+2; % n will always be a multiple of 2
while x<3.14
x=4*((-1).^n/(2*n+1)) +x; % the summation formula
end
disp(x)
end }
I want it such that my value of pi in this case 'x' is no greater than 1e-6 away from the actual value of pi. So when it satisfies this condition the script will cease. However my script gives me endless loop of 3.2 and it pissing me off, all day on this crap :S . Why is matlab so hard?????
Akzeptierte Antwort
Weitere Antworten (2)
Sean de Wolski
am 13 Dez. 2012
function myPi = piEst()
myPi = pi;
for ii = 1:0
myPi = myPi+ii;
end
end
4 Kommentare
A K
am 13 Dez. 2012
Sean de Wolski
am 13 Dez. 2012
I used a loop!
3.141592653589793238466 is still an approximation to actual pi. So my code meets all of your constraints!
A K
am 13 Dez. 2012
A K
am 13 Dez. 2012
0 Stimmen
Kategorien
Mehr zu Loops and Conditional Statements 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!