Clear Filters
Clear Filters

What's wrong with this code?

6 views (last 30 days)
Rasel Munshi
Rasel Munshi on 28 Jan 2018
Edited: Stephen23 on 28 Jan 2018
function sincomp(x,n)
i = 1;
tru = sin(x);
ser = 0;
fprintf('\n');
fprintf('order true value approximation error\n');
while (1)
if i > n, break, end
ser = ser + (-1)^(i - 1) * x^(2*i-1) / factorial(2*i-1);
err = (tru - ser) / tru * 100;
fprintf('%3d %14.10f %14.10f %12.8f\n',i,tru,ser,err);
i = i + 1;
end

Accepted Answer

Stephen23
Stephen23 on 28 Jan 2018
Edited: Stephen23 on 28 Jan 2018
Your basic idea is okay, but a few tweaks would make the code simpler and more robust. Because there is a clear practical limit to the number of iterations that are possible (limited by factorial) I would recommend using a for loop: this avoids any chance of an unintentional infinite loop (which is an easy trap to fall into with while loops), and means that you do not need to keep track of the loop variable yourself. So you would get:
N = 0.9;
Z = 0;
T = sin(N);
for k = 0:7 % 8 terms
p = k*2+1;
Z = Z + (-1)^k * (N^p / factorial(p));
fprintf('val =%+19.15f err =%+20.15f%%\n',Z,100*(T-Z)/T)
end
giving:
val = +0.900000000000000 err = -14.894559211300594%
val = +0.778500000000000 err = +0.616206282224993%
val = +0.783420750000000 err = -0.011979720262797%
val = +0.783325849821429 err = +0.000135295499462%
val = +0.783326917448438 err = -0.000000998427861%
val = +0.783326909586820 err = +0.000000005191053%
val = +0.783326909627640 err = -0.000000000020041%
val = +0.783326909627483 err = +0.000000000000057%
Addendum: It would really make more sense mathematically to calculate the error the other way around (i.e. Z-T, not T-Z):
fprintf('val =%+19.15f err =%+20.15f%%\n',Z,100*(Z-T)/T)
giving
val = +0.900000000000000 err = +14.894559211300594%
val = +0.778500000000000 err = -0.616206282224993%
val = +0.783420750000000 err = +0.011979720262797%
val = +0.783325849821429 err = -0.000135295499462%
val = +0.783326917448438 err = +0.000000998427861%
val = +0.783326909586820 err = -0.000000005191053%
val = +0.783326909627640 err = +0.000000000020041%
val = +0.783326909627483 err = -0.000000000000057%
because then V_est = V_true + V_true*err, e.g.:
>> sin(0.9) * (1+0.14894559211300594) % 1st term
ans = 0.900000000000000
>> sin(0.9) * (1-0.00616206282224993) % 2nd term
ans = 0.778500000000000
... etc
whereas as the question is written it makes no sense any way you look at it:
>> sin(0.9) * (1-0.14894559211300594)
ans = 0.666653819254967
>> 0.9 * (1-0.14894559211300594)
ans = 0.765948967098295
Whoever wrote the question did not consider the effect of removing the abs from the commonly used formula for relative error. Of course if they had kept the abs then this addendum would become moot.

More Answers (0)

Categories

Find more on Mathematics and Optimization 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!