-- bisection method for solving non-linear equationsdelta=1e-6-- tolerancefunctionbisect(f,a,b,fa,fb)localc=(a+b)/2io.write(n," c=",c," a=",a," b=",b,"\n")ifc==aorc==bormath.abs(a-b)<deltathenreturnc,b-aendn=n+1localfc=f(c)iffa*fc<0thenreturnbisect(f,a,c,fa,fc)elsereturnbisect(f,c,b,fc,fb)endend-- find root of f in the inverval [a,b]. needs f(a)*f(b)<0functionsolve(f,a,b)n=0localz,e=bisect(f,a,b,f(a),f(b))io.write(string.format("after %d steps, root is %.17g with error %.1e, f=%.1e\n",n,z,e,f(z)))end-- our functionfunctionf(x)returnx*x*x-x-1end-- find zero in [1,2]solve(f,1,2)