Imported from ../lua-3.0.tar.gz.
[lua.git] / test / bisect.lua
blob8b7206547e3ccba4c36605a6425b34b3b4c26fd8
1 $debug
2 -- bisection method for solving non-linear equations
4 function bisect(f,a,b,fa,fb)
5 write(n," a=",a," fa=",fa," b=",b," fb=",fb,"\n")
6 local c=(a+b)/2
7 if abs(a-b)<delta then return c end
8 n=n+1
9 local fc=f(c)
10 if fa*fc<0 then return bisect(f,a,c,fa,fc) else return bisect(f,c,b,fc,fb) end
11 end
13 -- find root of f in the inverval [a,b]. bisection needs that f(a)*f(b)<0
14 function solve(f,a,b)
15 delta=1e-6 -- tolerance
16 n=0
17 local z=bisect(f,a,b,f(a),f(b))
18 write(format("after %d steps, root is %.10g\n",n,z))
19 end
21 -- our function
22 function f(x)
23 return x*x*x-x-1
24 end
26 solve(f,1,2)