Hi! I need help with how I put an input in this program!

1 view (last 30 days)
Hi! I need help with this program (below).I need to put the n terms with an input, and I don't want that the graph behavior tends to infinity. Thanks a lot.
clear
clc
p = 0; % Start at 0
S = []; % Initiate array of approximations
i = 0;
while 1 == 1 % Infinite Loop
p = p + (4*((-1)^i))/(2*i + 1); % The Leibniz formula for pi: http://en.wikipedia.org/wiki/Leibniz_formula_for_pi
if rem(i,2) == 0 % Alternately set p1 and p2, then average them to find a better approximation
p1 = p;
S = [S p1]; % Append new value to array
if i > 9
plot(length(S)-10:length(S),S(length(S)-10:end))
axis([length(S)-10 length(S) 2 4])
pause(0.1)
else
plot(S)
axis([1 10 2 4])
pause(0.1)
end
else
p2 = p;
S = [S p2]; % Append new value to array
if i > 9
plot(length(S)-10:length(S),S(length(S)-10:end))
axis([length(S)-10 length(S) 2 4])
pause(0.1)
else
plot(S)
axis([1 10 2 4])
pause(0.1)
end
end
i = i + 1;
end

Answers (1)

Geoff Hayes
Geoff Hayes on 15 Oct 2016
Anthony - which n terms? Or do you only want the program to iterate for at most n times? If this is true, then just take your script and make it into a function that takes a single input: a maximum number of iterations. Something like
function myFunc(n)
Your while loop then becomes
while i < n
and your result S will have n elements. Since this is a function, make sure that you remove your call to clear.

Categories

Find more on Graphics Performance in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!