# Write a function [sn, n] = mySumPi(tol), which outputs 𝑆n and n for the smallest n such that |𝑆n − pi| < tol

1 view (last 30 days)
Anastasia Kyriakou on 22 Feb 2020

Anastasia Kyriakou on 22 Feb 2020
i have to write a code which outpous n and sn..
@David where do i have to write this?
what i have to change?
David Hill on 22 Feb 2020
Your equation does not match the one you are trying to code. You will need to initialize sn and n before starting your while loopo.
Anastasia Kyriakou on 22 Feb 2020
how? what can i write?

John D'Errico on 22 Feb 2020
Edited: John D'Errico on 22 Feb 2020
Ok, you are at least now getting close. Your code is still convoluted. And you have the wrong terms you create.
Look carefully at the term you need to create. It should apparently look like
1/((4*k-3)*(4*k-1))
You can multiply by 8, to cater to the 8 out front in the sum. But what you wrote is not that. Close. But not that. It still had sn in it, from the previous term.
As well, why are you computing count, but then returning n, which is just 1 less than count? Strange. Oh, I guess you are using n as the summation index, but it is not the number of terms you needed in the sum? But it is the number of terms.
Finally, you never actually initialized the approximation in any way at zero. Always initialize a sum variable that will accumulate a result. Just don't use a variable named sum.
And, oh. Learn to use semi-colons on your lines.
function [piapprox,k] = mySumPi(tol)
%[piapprox,k] = mySumPi(tol)
%lim as n approaches infinity is pi
% k is the index of the first term such that abs(piapprox-pi) <tol
k = 0;
piapprox = 0;
while abs(piapprox-pi) >= tol
k = k + 1;
piterm = 8./((4*k-3)*(4*k-1));
piapprox = piapprox + piterm;
end
end
With a tolerance of 1e-2, I get
[piapprox,count] = mySumPi(1e-2)
piapprox
piapprox =
3.13159290355855
k
k =
50
The series you are using is not very rapidly convergent. Better than a sharp stick in the eye, but not incredibly much better.

Anastasia Kyriakou on 22 Feb 2020
thank you very much but it says that n and sn must be the outputs.
Anastasia Kyriakou on 22 Feb 2020
i found the answer thanks anyway