summaryrefslogtreecommitdiff
path: root/test/bisect.lua
diff options
context:
space:
mode:
authorLua Team <team@lua.org>1996-05-14 12:00:00 +0000
committerrepogen <>1996-05-14 12:00:00 +0000
commit721542976ebc89f2f8d17d19be7e4426570b69be (patch)
tree0c79a45c63aa89d6e4b8ac80931e46d74a72f8cb /test/bisect.lua
parent71754d2f6423fb9b6e87658e58bafc5470d53f65 (diff)
downloadlua-github-2.4.tar.gz
Lua 2.42.4
Diffstat (limited to 'test/bisect.lua')
-rw-r--r--test/bisect.lua26
1 files changed, 26 insertions, 0 deletions
diff --git a/test/bisect.lua b/test/bisect.lua
new file mode 100644
index 00000000..cfb1bbfd
--- /dev/null
+++ b/test/bisect.lua
@@ -0,0 +1,26 @@
+$debug
+-- bisection method for solving non-linear equations
+
+function bisect(f,a,b,fa,fb)
+print(n.." a="..a.." fa="..fa.." b="..b.." fb="..fb)
+ local c=(a+b)/2
+ if abs(a-b)<delta then return c 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
+function solve(f,a,b)
+ delta=1e-6 -- tolerance
+ n=0
+ local z=bisect(f,a,b,f(a),f(b))
+ print(format("after %d steps, root is %.10g",n,z))
+end
+
+-- our function
+function f(x)
+ return x*x*x-x-1
+end
+
+solve(f,1,2)