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