The while loop for my taylor expansion will not check the condition for each iteration.

1 次查看(过去 30 天)
c = pi;
x = (12*pi)/17;
f = x + 1.9 + 0.158*sin(x); %original equation f
f1 = 1 + 0.158*cos(x); %derivative 1
f2 = -0.158*sin(x); %derivative 2
f3 = -0.158*cos(x); %derivative 3
f4 = 0.158*sin(x); %derivative 4
f5 = 0.158*cos(x); %derivative 5 Note: derivative 4 and 5 wll flip for eternity
real_value = c + 1.9 + 0.158*sin(c);
i = 1;
MAXerror = 1;
while MAXerror >= 0.0000001 %while loop will execute until all values stored in variable c is approximated under an error of 0.00001%
if i == 1
f_taylor(i) = f; %0th order taylor
Et(i) = abs(real_value - f_taylor(i))/real_value;
elseif i == 2
f_taylor(i) = f_taylor(i - 1) + f1.*((c - x).^(i-1)); %1st order taylor
Et(i) = abs(real_value - f_taylor(i))/real_value;
elseif i == 3
f_taylor(i) = f_taylor(i - 1) + (f2/factorial(i-1)).*((c - x).^(i-1)); %2nd order taylor
Et(i) = abs(real_value - f_taylor(i))/real_value;
elseif i == 4
f_taylor(i) = f_taylor(i - 1) + (f3/factorial(i-1)).*((c - x).^(i-1)); %3rd order taylor
Et(i) = abs(real_value - f_taylor(i))/real_value;
elseif i == 5
f_taylor(i) = f_taylor(i - 1) + (f4/factorial(i-1)).*((c - x).^(i-1)); %4th order taylor
Et(i) = abs(real_value - f_taylor(i))/real_value;
elseif mod(i,2) == 0
f_taylor(i) = f_taylor(i - 1) + (f5/factorial(i - 1)).*((c - x).^(i - 1)); %5th order taylor and will cover all odd orders from here on
Et(i) = abs(real_value - f_taylor(i))/real_value;
elseif i > 10000
fprintf('break')
break
else
f_taylor(i) = f_taylor(i - 1) + (f5/factorial(i - 1)).*((c - x).^(i - 1)); %6th order taylor and will cover all even orders from here on
Et(i) = abs(real_value - f_taylor(i))/real_value;
end
MAXerror = Et(i); %determines the maximum error value in each taylor order
i = i + 1;
end
The loop goes to the maximum i (1000) but should be finished wihin the first 8 loops based on the condition. Debugging found out that the while loop conditon is not checked after the first loop.

回答(1 个)

Geoff Hayes
Geoff Hayes 2021-10-6
@Zachary Nies - I don't think your MAXerror ever gets below the condition. When I run your code, the minimum value assigned to it is
4.04848575875934e-07
which is still greater
0.000000404848575875934 >= 0.0000001
As an aside, is it necessary to have separate if/elseif conditions for i equal to 1, 2, 3, 4 and 5? Can't you just generalize for even and odd i?

类别

Help CenterFile Exchange 中查找有关 Spectral Measurements 的更多信息

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by