| 1 | -- bisect.lua |
| 2 | -- bisection method for solving non-linear equations |
| 3 | |
| 4 | delta=1e-6 -- tolerance |
| 5 | |
| 6 | function bisect(f,a,b,fa,fb) |
| 7 | local c=(a+b)/2 |
| 8 | io.write(n," c=",c," a=",a," b=",b,"\n") |
| 9 | if c==a or c==b or math.abs(a-b)<delta then return c,b-a end |
| 10 | n=n+1 |
| 11 | local fc=f(c) |
| 12 | if fa*fc<0 then return bisect(f,a,c,fa,fc) else return bisect(f,c,b,fc,fb) end |
| 13 | end |
| 14 | |
| 15 | -- find root of f in the inverval [a,b]. needs f(a)*f(b)<0 |
| 16 | function solve(f,a,b) |
| 17 | n=0 |
| 18 | local z,e=bisect(f,a,b,f(a),f(b)) |
| 19 | io.write(string.format("after %d steps, root is %.17g with error %.1e, f=%.1e\n",n,z,e,f(z))) |
| 20 | end |
| 21 | |
| 22 | -- our function |
| 23 | function f(x) |
| 24 | return x*x*x-x-1 |
| 25 | end |
| 26 | |
| 27 | -- find zero in [1,2] |
| 28 | solve(f,1,2) |