bisect.lua 645 B

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