Why is the loop infinite?

5 vues (au cours des 30 derniers jours)
Jacob Savona
Jacob Savona le 12 Mar 2015
Réponse apportée : ag le 29 Jan 2025 à 16:57
Trying to do False Position method for the taylor series expansion of sin(x)= sigma(sum)]k=0=inf ((-1^k)/(2*p+1)!)*((x)^(2*k+1)). Input k, bounds between a small number>0 and 3pi/2, Error<.0001. Function should also find the error between the root of the series and the actual root of the function. Error = abs(actual_value-estimate/ actual_value)Actual root should equal pi/2 because I'm solving for sin(x)=0 right? There are two outputs for the function, the estimate root and the error of the root. On one figure plot: 1) Sin(x)-- 2) The polynomial produced from the first k terms of the Taylor expansion-- 3) The false position guesses-- 4). The actual root of sin(x) Code:
function [root,root_error]= HW7_JAS_2(k)
x_lower=.000001;%initial lower bound
x_upper=(3*pi)/2;%initial upper bound
x_true=pi/2;%actual value for x
x_root=0;
lower_b=zeros(1,k+1);
upper_b=zeros(1,k+1);
it=1;
while abs((x_true-x_root)/x_true) > .0001
for p=0:k
lower_b(p+1)=((-1^p)/factorial(2*p+1))*((x_lower).^(2*p+1));%put through taylor series expansion
upper_b(p+1)=((-1^p)/factorial(2*p+1))*((x_upper).^(2*p+1));%put through taylor series expansion
end
sumlower_b=sum(lower_b);%f(lower bound)
sumupper_b=sum(upper_b);%f(upper bound)
x_root=(x_upper)-(((sumlower_b)*(x_lower-x_upper))/(sumlower_b-sumupper_b));%calculates root
fx_root=sin(x_root);%f(root)
if lower_b * fx_root <0
x_upper= x_root;
elseif upper_b * fx_root <0
x_lower= x_root;
elseif lower_b * fx_root ==0
root = x_root;
end
plot(it,x_root,'g*');%plots false position guesses
hold on%allows each guess to be plotted
xlabel('Iterations');
ylabel('Estimated time values');
legend('Iterations vs Estimated time values');
it=it+1;%new iteration
end
root_error= abs((x_true-x_root)/x_true);%error in the root
x=0:.1:2*pi;
plot(x,sin(x),'r-');
xlabel('x values');
ylabel('sin(x) values');
legend('sin(x)');
hold on
x1=0:.1:root;
plot(x1,sin(root),'b-');
xlabel('x values stopped at root value');
ylabel('sin(x) values stopped at sin(root)');
legend('sin(root)');% The polynomial produced from the first k terms of the Taylor expansion
hold on
plot(x_true,sin(x_true),'yx');
xlabel('x values');
ylabel('y values');
legend('Real root of sin(x)');
end
Posted this earlier but the website deleted it for some reason. Thanks for any help. Posted

Réponses (1)

ag
ag le 29 Jan 2025 à 16:57
Hi Jacob,
I understand that you are facing an infinite loop issue in the above provided code. Below are my observations on the code which can be fixed to resolve this issue:
  • The code references (\pi/2) as the actual root for (\sin(x) = 0). However, within the interval specified, the correct root should be (\pi), as zeros of (\sin(x)) occur at (n\pi) for integer values of (n).
  • The evaluation of the Taylor series for (\sin(x)) does not correctly sum the terms up to the specified (k). This affects the accuracy of the approximation.
  • The conditions checking the product of lower_b and fx_root are incorrect, as lower_b and upper_b are arrays rather than scalar function evaluations.
  • The logic for updating bounds in the False Position method needs refinement to ensure it correctly determines the subinterval containing the root.
  • The plotting commands are not properly structured to accommodate multiple plots and legends. This may lead to confusion in visualizing the polynomial approximation and the actual root.
Below is a modified version of your code with sefl explanatory comments addressing the above issues:
function [root, root_error] = HW7_JAS_2(k)
% Define bounds
x_lower = 0.000001; % Initial lower bound
x_upper = (3 * pi) / 2; % Initial upper bound
x_true = pi; % Correct root for sin(x) = 0 within the given range
% Initialize variables
x_root = 0;
it = 1;
max_iter = 1000; % Limit iterations to prevent infinite loops
% Define the Taylor series function for sin(x)
taylor_sin = @(x) sum(arrayfun(@(p) ((-1)^p / factorial(2*p+1)) * x^(2*p+1), 0:k));
% Plot settings
figure;
hold on;
x = linspace(0, 2*pi, 1000);
plot(x, sin(x), 'r-', 'DisplayName', 'sin(x)'); % Plot sin(x)
xlabel('x values');
ylabel('Function values');
legend show;
% False Position Method Loop
while abs((x_true - x_root) / x_true) > 0.0001 && it <= max_iter
% Evaluate the Taylor series at the bounds
f_lower = taylor_sin(x_lower);
f_upper = taylor_sin(x_upper);
% Calculate the root using the False Position formula
x_root = x_upper - (f_upper * (x_lower - x_upper)) / (f_lower - f_upper);
% Evaluate the Taylor series at the new root
f_root = taylor_sin(x_root);
% Plot the current guess
plot(x_root, 0, 'g*', 'DisplayName', sprintf('Iteration %d', it));
% Determine which subinterval to use
if f_lower * f_root < 0
x_upper = x_root;
else
x_lower = x_root;
end
it = it + 1;
end
% Calculate the error
root_error = abs((x_true - x_root) / x_true);
% Plot the polynomial approximation
y_taylor = arrayfun(taylor_sin, x);
plot(x, y_taylor, 'b--', 'DisplayName', 'Taylor Series Approximation');
% Plot the actual root
plot(x_true, 0, 'yx', 'MarkerSize', 10, 'DisplayName', 'Actual Root');
% Output results
fprintf('Estimated Root: %.6f\n', x_root);
fprintf('Root Error: %.6f\n', root_error);
hold off;
end
Hope this helps!

Community Treasure Hunt

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

Start Hunting!

Translated by