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!