1 -- bisection method for solving non-linear equations
3 delta
=1e-6 -- tolerance
5 function bisect(f
,a
,b
,fa
,fb
)
7 io
.write(n
," c=",c
," a=",a
," b=",b
,"\n")
8 if c
==a
or c
==b
or math
.abs(a
-b
)<delta
then return c
,b
-a
end
11 if fa
*fc
<0 then return bisect(f
,a
,c
,fa
,fc
) else return bisect(f
,c
,b
,fc
,fb
) end
14 -- find root of f in the inverval [a,b]. needs f(a)*f(b)<0
17 local z
,e
=bisect(f
,a
,b
,f(a
),f(b
))
18 io
.write(string.format("after %d steps, root is %.17g with error %.1e, f=%.1e\n",n
,z
,e
,f(z
)))