Reputation: 11
This is my Matlab code:
clear;clc;format ('long','g')
i=1;
x(i)=0;
error(i) = 9999;
while error(i) >= 0.05
x(i+1) = (0.2062129)*(20+(2*x(i)))^(2/5);
error(i+1)=abs((((x(i+1)-x(i))/(x(i+1)))*100));
i=i+1;
end
disp(' root error(%)');
disp([x',error'])
How do I translate this into Mathematica so that it generates the list of roots and errors the way it does in matlab?
Upvotes: 0
Views: 111
Reputation: 6989
I'd suggest instead of burying the convergence test in the function you do like this:
f[xi_] := 0.2062129*(20 + (2*xi))^(2/5)
NestWhileList[f, 0, Abs[(#2 - #1)/#2*100] >= .05 &, 2]
{0, 0.683483, 0.701799, 0.70228, 0.702293}
You can also do:
FixedPointList[f, 0, SameTest -> (Abs[(#2 - #1)/#2*100] < .05 &)]
Note in both cases you can use FixedPoint
and NestWhile
if you just want the final result , not the list of intermediate values.
Upvotes: 0
Reputation: 3957
Since we don't have the output you got from Matlab it is difficult to know whether this is correct enough or not. Compare it to what you have and go from there.
expr={1,0,9999};
f[{i_,xi_,err_}]:=(xipp=0.2062129*(20+(2*xi))^(2/5);
{i+1,xipp,Abs[(((xipp-xi)/(xipp))*100)]});
NestWhileList[f,expr,#[[3]]>=.05&]
which in a fraction of a second returns
{{1,0,9999},
{2,0.683483,100.},
{3,0.701799,2.60989},
{4,0.70228,0.0684954},
{5,0.702293,0.00179788}}
Upvotes: 1