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