R = 3;
V_desired = 30; % Desired volume
x1 = 4; % Initial guess
x2 = 3; % Second initial guess
number_iterations = 50;
syms hh
% Solve for exact solution
eqn = pi*hh^2*(3*R-hh)/3 == V_desired;
ans = solve(eqn, hh);
answ = double(ans(2)); % Choose the appropriate root
rj = answ; % Exact solution
matrix = zeros(number_iterations, 3); % Preallocate matrix
for iterations = 1:number_iterations
fx1 = volume(x1, R, V_desired);
fx2 = volume(x2, R, V_desired);
if (fx2 - fx1) == 0
break; % Avoid division by zero
end
x3 = (x1*fx2 - x2*fx1) / (fx2 - fx1);
error = abs((rj - x3)/rj)*100;
matrix(iterations, 1) = iterations;
matrix(iterations, 2) = x3;
matrix(iterations, 3) = error;
% Update for next iteration
x1 = x2;
x2 = x3;
% Break if the solution has effectively converged
if error < 1e-6
matrix = matrix(1:iterations, :); % Trim the matrix
break;
end
end
disp(matrix);
function vol = volume(h, R, V_desired)
% Calculate volume difference from desired
vol = pi*h^2*(3*R-h)/3 - V_desired;
end
Remember, the choice of initial guesses (x1 and x2) significantly affects the convergence of the secant method, so make sure they are reasonable based on the physical problem. If the method still fails to converge, consider using different initial guesses or a more robust root-finding method.
------------------------------------------------------------------------------------------------------------------------------------------------
If you find the solution helpful and it resolves your issue, it would be greatly appreciated if you could accept the answer. Also, leaving an upvote and a comment are also wonderful ways to provide feedback.
Professional Interests
- Technical Services and Consulting
- Embedded Systems | Firmware Developement | Simulations
- Electrical and Electronics Engineering