Info

This question is closed. Reopen it to edit or answer.

If possible, can someone please help me fix this function so I can find the roots of a certain function?

1 view (last 30 days)
In the attachments is a picture of my function. I am trying to write a function that will find the roots of a function given an initial guess "x". I want to make a while statement so the function keeps on repeating until the function gets the correct value of x, such that the tolerance is 1*10^-10. If anyone can help me it'll be greatly appreciated.
NOTE: I was trying to mimic my professors code. The first code is mine with the function f(x)=sin(x)+[(2e^(x/10)*cos(x)]-3 and the initial guess x is 5. The solution should be outputting x ≈ 5.91061140513925.
My professors code is below mine with the function f(E) = E-esin(E)-M; where e is eccentricity. His initial guess is the value of M.
MY CODE FUNCTION
% fx4 = root(x)
function fx4 = root(x)
MAXITER = 100; % in case the loop does not converge
TOL = 1e-10; % tolerance for convergence
x4 = 5; % first guess
fx4 = sin(x)+(2*exp(x/10)*cos(x))-3; % f(x) that we want to be zero
iter = 1; % count the iterations
while ( abs(fx4) > TOL )
fx4 = sin(x)+(2*exp(x/10)*cos(x))-3;
iter = iter+1;
if (iter>=MAXITER)
error('Did not converge');
exit
end
end
end
MY Professors CODE
% E = keplersolve(M,e)
function E = keplersolve(M,e)
MAXITER = 100; % in case the loop does not converge
TOL = 1e-11; % tolerance for convergence
En = M; % first guess
fn = En - e*sin(En) - M; % f(E) that we want to be zero
iter = 1; % count the iterations
while ( abs(fn) > TOL )
En = En - fn/(1-e*cos(En));
fn = En - e*sin(En) - M;
iter = iter+1;
if (iter>=MAXITER)
error('Did not converge');
exit
end
end
E = En
end
  1 Comment
OCDER
OCDER on 16 Oct 2017
How are you adjusting and using x4 in your code per iteration? Also, use the {}Code button in this Matlab Answer text box to make your code more readable like this :
TOL = 1e-10;
x4 = 5; % first guess ** BUT, This is not used and updated per loop! **
fx4 = sin(x)+(2*exp(x/10)*cos(x))-3;
iter = 1;

Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!