Roots of a function: Difference between revisions
Content added Content deleted
m (→{{header|Lua}}: typo) |
(→{{header|Lua}}: added code comments) |
||
Line 1,356: | Line 1,356: | ||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
<lang Lua> |
<lang Lua>-- Function to have roots found |
||
function f (x) return x^3 - 3*x^2 + 2*x end |
|||
-- Finds roots of f within range x=[start, stop] or approximations thereof |
|||
function root (f, start, stop, step) |
function root (f, start, stop, step) |
||
local roots, x, sign, foundExact, value = {}, start, f(start) > 0, false |
local roots, x, sign, foundExact, value = {}, start, f(start) > 0, false |
||
Line 1,365: | Line 1,367: | ||
table.insert(roots, {val = x, err = 0}) |
table.insert(roots, {val = x, err = 0}) |
||
foundExact = true |
foundExact = true |
||
end |
|||
if value > 0 ~= sign then |
|||
if foundExact then |
if foundExact then |
||
foundExact = false |
foundExact = false |
||
Line 1,378: | Line 1,381: | ||
end |
end |
||
-- Main procedure |
|||
print("Root (to 12DP)\tMax. Error\n") |
print("Root (to 12DP)\tMax. Error\n") |
||
for _, r in pairs(root(f, -1, 3, 10^-6)) do |
for _, r in pairs(root(f, -1, 3, 10^-6)) do |
||
Line 1,389: | Line 1,393: | ||
2.000000999934 1e-06</pre> |
2.000000999934 1e-06</pre> |
||
Note that the roots found are all near misses because fractional numbers that seem nice and 'round' in decimal (such as 10^-6) often have some rounding error when represented in binary. To increase the chances of finding exact integer roots, try using an integer start value with a step value that is a power of two. |
Note that the roots found are all near misses because fractional numbers that seem nice and 'round' in decimal (such as 10^-6) often have some rounding error when represented in binary. To increase the chances of finding exact integer roots, try using an integer start value with a step value that is a power of two. |
||
<lang Lua> |
<lang Lua>-- Main procedure |
||
print("Root (to 12DP)\tMax. Error\n") |
|||
for _, r in pairs(root(f, -1, 3, 2^-10)) do |
for _, r in pairs(root(f, -1, 3, 2^-10)) do |
||
print(string.format("%0.12f", r.val), r.err) |
print(string.format("%0.12f", r.val), r.err) |