Incorrect number comparison result (Lua)

33 Views Asked by At

How can I make the examples return the result "true".

What are my mistakes?

MWE:

local arr = {{a = 1,   b = 3,    op = ">=",    c = 7},
            {a = 1,   b = 3,    op = "<=",    c = 6}}
local str1, str2, x1, x2, i
x1 = 0
x2 = 2 + 1/3 -- 2.(3)
i = 1
str1 = arr[i].a .. "*" .. tostring(x1) .. "+" .. arr[i].b .. "*" .. tostring(x2) .. arr[i].op .. arr[i].c
str2 = arr[i].a .. "*" .. tostring(x1) .. "+" .. arr[i].b .. "*" .. tostring(x2)
f = loadstring("return " .. str1)
f1 = loadstring("return " .. str2)
print(str1, f(), str2 .. " = " .. f1()) -- It doesn't work that way
print(0 + 3 * (2 + 1/3), 7, 0 + 3 * (2 + 1/3) >= 7) -- And here it seems similar, but everything works
x1 = 1.2
x2 = 1.6
i = 2
str1 = arr[i].a .. "*" .. tostring(x1) .. "+" .. arr[i].b .. "*" .. tostring(x2) .. arr[i].op .. arr[i].c
str2 = arr[i].a .. "*" .. tostring(x1) .. "+" .. arr[i].b .. "*" .. tostring(x2)
f = loadstring("return " .. str1)
f1 = loadstring("return " .. str2)
print(str1, f(), str2 .. " = " .. f1()) -- It’s completely unclear here! It turns out 6 is not equal to 6

I get this result:

enter image description here

I used the manual number comparison function. Its code is presented below. This solution seemed to allow me to do what I needed.

local function compare(a, b, epsilon, comparison)
if comparison == "==" then
  return math.abs(a - b) < epsilon
elseif comparison == "<" then
  return a < b - epsilon
elseif comparison == "<=" then
  return a <= b + epsilon
elseif comparison == ">" then
  return a > b + epsilon
elseif comparison == ">=" then
  return a >= b - epsilon
else
  error("Invalid comparison operator: " .. comparison)
end
end
0

There are 0 best solutions below