Roots of a function: Difference between revisions

Added Easylang
(Added Easylang)
 
(3 intermediate revisions by 3 users not shown)
Line 163:
3rd root found at x = 0.0000000000000000000000e 0 (Exactly)
</pre>
 
=={{header|Arturo}}==
<syntaxhighlight lang="arturo">f: function [n]->
((n^3) - 3*n^2) + 2*n
 
 
step: 0.01
start: neg 1.0
stop: 3.0
sign: positive? f start
x: start
 
while [x =< stop][
value: f x
 
if? value = 0 ->
print ["root found at" to :string .format:".5f" x]
else ->
if sign <> value > 0 -> print ["root found near" to :string .format:".5f" x]
sign: value > 0
'x + step
]</syntaxhighlight>
 
{{out}}
 
<pre>root found near 0.00000
root found near 1.00000
root found near 2.00000</pre>
 
=={{header|ATS}}==
Line 998 ⟶ 1,027:
x += fstep;
end;</syntaxhighlight>
 
=={{header|EasyLang}}==
<syntaxhighlight>
func f x .
return x * x * x - 3 * x * x + 2 * x
.
numfmt 6 0
proc findroot start stop step . .
x = start
while x <= stop
val = f x
if val = 0
print x & " (exact)"
elif sign val <> sign0 and sign0 <> 0
print x & " (err = " & step & ")"
.
sign0 = sign val
x += step
.
.
proc drawfunc start stop . .
linewidth 0.3
drawgrid
x = start
while x <= stop
line x * 10 + 50 f x * 10 + 50
x += 0.1
.
.
drawfunc -1 3
findroot -1 3 pow 2 -20
print ""
findroot -1 3 1e-6
</syntaxhighlight>
 
=={{header|EchoLisp}}==
Line 3,470 ⟶ 3,533:
{{trans|Go}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="ecmascriptwren">import "./fmt" for Fmt
 
var secant = Fn.new { |f, x0, x1|
Line 3,506 ⟶ 3,569:
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>
1,978

edits