-- bisection method for solving non-linear equations delta=1e-666 local _tostring=tostring function tostring(x) if type(x)=="number" then return string.format("%.17g",x) else return _tostring(x) end end function places(x,y) x=tostring(x) y=tostring(y) for n=0,#y do --print(n,x:sub(1,n),y:sub(1,n)) if x:sub(1,n)~=y:sub(1,n) then return n-3 end end return #y end function bisect(f,a,b,dir) local c=(a+b)/2 print(n,dir,places(c,root),math.floor(-math.log10(math.abs(a-b)/2)),c) if c==a or c==b or math.abs(a-b)0 then return bisect(f,a,c,"L") else return bisect(f,c,b,"R") end end function solve(f,a,b,r) n=0 root=r if f(a)>0 then a,b=b,a end local r,e=bisect(f,a,b,"I") io.write(string.format("after %d steps, root is %.17g with error %.1e, f=%.1e\n",n,r,e,f(r))) print(r,r-root,r==root) return r end function f(x) return math.tan(x/4)-1 end solve(f,0,4,math.pi) function f(x) return x^2-2 end solve(f,0,4,math.sqrt(2)) function f(x) return x^2-2 end solve(f,4,0,math.sqrt(2)) a=1+2^(-20) function f(x) return x-a end solve(f,0,4,a) function f(x) return (x-1)*(x-2)*(x-3) end solve(f,0,4,2) for b=1,100,2^-3 do print("BA",b,solve(f,0,b,0)) end do return end