Jump to content

Roots of a function: Difference between revisions

Added XPL0 example.
(added Arturo)
(Added XPL0 example.)
Line 3,535:
findRoots.call(example, -0.5, 2.6, 1)</syntaxhighlight>
 
{{out}}
<pre>
0.000 approximate
1.000 exact
2.000 approximate
</pre>
 
=={{header|XPL0}}==
{{trans|Wren}}
<syntaxhighlight lang "XPL0">include xpllib; \for Print
 
func real F(X);
real X;
return X*X*X - 3.*X*X + 2.*X;
 
char Status;
 
func real Secant(X0, X1);
real X0, X1, F0, F1, T;
int I;
[F1:= F(X0);
for I:= 0 to 100-1 do
[F0:= F1;
F1:= F(X1);
if F1 = 0. then [Status:= "exact"; return X1];
if abs(X1-X0) < 1e-6 then [Status:= "approximate"; return X1];
T:= X0;
X0:= X1;
X1:= X1 - F1*(X1-T)/(F1-F0);
];
Status:= 0; return 0.;
];
 
func FindRoots(Lower, Upper, Step);
real Lower, Upper, Step;
real X0, X1, R;
[X0:= Lower;
X1:= Lower + Step;
while X0 < Upper do
[X1:= if X1 < Upper then X1 else Upper;
R:= Secant(X0, X1);
if Status # 0 and R >= X0 and R < X1 then
Print(" %2.3f %s\n", R, Status);
X0:= X1;
X1:= X1 + Step;
];
];
 
FindRoots(-0.5, 2.6, 1.)</syntaxhighlight>
{{out}}
<pre>
295

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.