bisect.lua
来自「这个是脚本引擎lua的例程,这是一个嵌入式的袖珍引擎」· LUA 代码 · 共 28 行
LUA
28 行
-- bisection method for solving non-linear equationsdelta=1e-6 -- tolerancefunction bisect(f,a,b,fa,fb) local c=(a+b)/2 io.write(n," c=",c," a=",a," b=",b,"\n") if c==a or c==b or math.abs(a-b)<delta then return c,b-a end n=n+1 local fc=f(c) if fa*fc<0 then return bisect(f,a,c,fa,fc) else return bisect(f,c,b,fc,fb) endend-- find root of f in the inverval [a,b]. needs f(a)*f(b)<0function solve(f,a,b) n=0 local z,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 functionfunction f(x) return x*x*x-x-1end-- find zero in [1,2]solve(f,1,2)
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?