
Originally Posted by
Kaktusse
I have 2 questions I need help with;
Question 1: 355 / 113 is a good approximation of pi. Let p and q be positive integer. Write a Matlab program to find the lowest value of q (and attached p) that meets the condition | p / q - pi | < | 355 / 113 - pi | Trying for a solution;
First of all, 113 needs to be one step more (114). If we take pi away, we get a negative number which is a sign that we need to increase 355. Do this until we get positive numbers again (when we look at the new error at the new fraction), then we increase 355 with 1 (and so on). Everytime we change, we also look if abs(newerror) < abs(old error)
code:
Code:
function [t, n, err] = fracpi(t0, n0)
e0 = t0/n0-pi;
t = t0;
n = n0;
while (1)
frac = t/n;
if abs(frac-pi) < abs(e0), break, end
if frac-pi < 0
t=t+1;
else
n=n+1;
end
end
err = frac-pi;
end
I thought this would be right. But Matlab tells its wrong.
How does Matlab tell you this is wrong (it looks OK in principle)? You might try:
Code:
function [t, n, err] = fracpi(t0, n0)
e0 = t0/n0-pi;
t = t0;
n = n0;
while (1)
frac = t/n;
err=frac-pi;
if abs(err) < abs(e0)
return
end
if err < 0
t=t+1;
else
n=n+1;
end
end
end
CB