Reputation: 11
I have a equation f(x)=exp(x)+3x^2
, f(x)=0
, x=?
then I use scilab
to solve that equation using fixed point iteration this is my code
function fixed_point(fung,x0,err)
x=zeros(100);
ea = 100;
i = 1;
x(i)=x0;
printf(" \t i \t x(i) \t ea(%%)");
printf("\n\t %d \t %f \t %f", i, x(i), abs(ea));
while (abs(ea) >err) do
i=i+1;
z =x(i-1);
x(i) = evstr(fung)+z;
ea =100*(x(i)-x(i-1))/x(i);
printf("\n\t %d \t %f \t %f", i, x(i), abs(ea));
end
printf("\n Akar = %f", x(i));
endfunction
then I call it using:
fixed_point ('exp(z)-(3 .* z .*z)',0.00000000001,0.5)
I got x(i)=inf
at last, but I think that's not the answer, can someone explain to me what's wrong with my code?
Upvotes: 1
Views: 1982
Reputation: 1172
Let's divide the answer to "subproblems":
In general: don't use numerical methods if you don't have an idea of solution. As Daniel showed, this equation doesn't have any solution in reals. If you have a reasonable x0, plot its neighborhood first!
In general: is your goal solving the equation or implementing that method? Matlab has e.g. fsolve
function (and you've added matlab tag as well as scilab) or, if you want to design your own function, the Newton's method works pretty well on these easily differentiable functions (sin, exp, x^n...).
In particular: add to your code something that allow you to escape the while loop if the solution doesn't converge. Than your output should be "DOESN'T CONVERGE" which is definitely better than the mysterious inf
(e.g. break the loop if i>1e3
or something like that).
Upvotes: 1