Imported from ../lua-3.1.tar.gz.
[lua.git] / test / bisect.lua
blob4de9e99b8db4fa14db762a203bfb4645428616ee
1 -- bisection method for solving non-linear equations
3 function bisect(f,a,b,fa,fb)
4 write(n," a=",a," fa=",fa," b=",b," fb=",fb,"\n")
5 local c=(a+b)/2
6 if c==a or c==b then return c end
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-9 -- tolerance
16 n=0
17 local z=bisect(f,a,b,f(a),f(b))
18 write(format("after %d steps, root is %.10g, f=%g\n",n,z,f(z)))
19 end
21 -- our function
22 function f(x)
23 return x*x*x-x-1
24 end
26 solve(f,1,2)