summaryrefslogtreecommitdiff
path: root/test/bisect.lua
diff options
context:
space:
mode:
authorLua Team <team@lua.org>2003-04-11 12:00:00 +0000
committerrepogen <>2003-04-11 12:00:00 +0000
commitf0e4e22f5c119865eb5a8d3844a40df2d5980b3b (patch)
treec4df063a747e9c99f8aba1678588a030993780a9 /test/bisect.lua
parent1981b7c90eb09e956e969cda5c473be4560af573 (diff)
downloadlua-github-f0e4e22f5c119865eb5a8d3844a40df2d5980b3b.tar.gz
Lua 5.05.0
Diffstat (limited to 'test/bisect.lua')
-rw-r--r--test/bisect.lua16
1 files changed, 7 insertions, 9 deletions
diff --git a/test/bisect.lua b/test/bisect.lua
index 9e1d8f70..f91e69bf 100644
--- a/test/bisect.lua
+++ b/test/bisect.lua
@@ -1,25 +1,23 @@
-- bisection method for solving non-linear equations
+delta=1e-6 -- tolerance
+
function bisect(f,a,b,fa,fb)
- write(n," a=",a," fa=",fa," b=",b," fb=",fb,"\n")
local c=(a+b)/2
- if c==a or c==b then return c end
- if abs(a-b)<delta then return c end
+ 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) end
end
--- find root of f in the inverval [a,b]. bisection needs that f(a)*f(b)<0
+-- find root of f in the inverval [a,b]. needs f(a)*f(b)<0
function solve(f,a,b)
- delta=1e-9 -- tolerance
n=0
- local z=bisect(f,a,b,f(a),f(b))
- write(format("after %d steps, root is %.10g, f=%g\n",n,z,f(z)))
+ 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
--- an example
-
-- our function
function f(x)
return x*x*x-x-1