Hi! I need help with a loop!
1 view (last 30 days)
Show older comments
I need help with my function that it is about the Wallis product: [pi/2= 2/1∗2/3∗4/3∗4/5∗6/5∗...], to estimate the value of pi. The function must do, that the user put the numbers of terms (t-input), and it return the value of pi estimated.(z-output)I did a function, but the problem is for example: if a put a even number like 4, it calculates only the multiplication of the terms 3 and 4, but erase the values of the previous terms. Also, it can't calculated it with odd numbers because I don't know how to remove the even term that is multiplicated. For example: if I put the number 4: the correct value it suppose to be 1.42 but it calculates the 3 and 4 multiplication that is 1.06 and is missing the multiplication of the first terms.I need help with this one, this is not my concentration, but I have a project that I need to do to increase my grades, Can you help me in anything?. Thanks a lot! t The function is the following:
function [z]=wallisproduct(t)
for k=t-t/2 %here is the problem: it use only the final terms (the final change/results of the loop) of the equation with a given t (input)
b=1;
P1=b*((2*k/(2*k-1))); %calculate the first term
terpar=b*(2*k/(2*k+1)); %calculate the second term
z=terpar*P1;
end
z=z*z;
if rem(t,2)==0;
disp(z);
else
end
0 Comments
Answers (1)
Alexandra Harkai
on 31 Oct 2016
There is no loop, because k only gets value of t-t/2=t/2 and none of the preceding ones. Changing that to k=1:t would give you the looping the way it is expressed here on the Wiki page.
The formula then needs to change to take either the first or the second term, depending on whether the current k is even or odd.
function [z] = wallisproduct(t)
z = 1; % initialise z to be used for the multiplicative steps
for k = 1:t
b = floor((k+1)/2); % find 'half' of k: 1 for 1 and 2, 2 for 3 and 4, 3 for 5 and 6, etc.
if mod(k, 2) % if k is odd, then mod(k, 2) is 1 which is true
z = z * 2*b /(2*b-1); %
else % if k is even, then mod(k, 2) is 0 which is false
z = z * 2*b /(2*b+1);
end
end
end
This then gives:
wallisproduct(4)
ans =
1.4222
0 Comments
See Also
Categories
Find more on Function Creation in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!