30 lines
795 B
Text
30 lines
795 B
Text
local fmt = require "fmt"
|
|
|
|
local function secant(f, x0, x1)
|
|
local f0 = 0
|
|
local f1 = f(x0)
|
|
for _ = 1, 100 do
|
|
f0 = f1
|
|
f1 = f(x1)
|
|
if f1 == 0 then return x1, "exact" end
|
|
if math.abs(x1 - x0) < 1e-6 then return x1, "approximate" end
|
|
x0, x1 = x1, x1 - f1 * (x1 - x0) / (f1 - f0)
|
|
end
|
|
return 0, ""
|
|
end
|
|
|
|
local function find_roots(f, lower, upper, step)
|
|
local x0 = lower
|
|
local x1 = lower + step
|
|
while x0 < upper do
|
|
x1 = (x1 < upper) ? x1 : upper
|
|
local r, status = secant(f, x0, x1)
|
|
if status != "" and x0 <= r < x1 then
|
|
fmt.print(" %6.3f %s", r, status)
|
|
end
|
|
x0, x1 = x1, x1 + step
|
|
end
|
|
end
|
|
|
|
local example = |x| -> x * x * x - 3 * x * x + 2 * x
|
|
find_roots(example, -0.5, 2.6, 1)
|