Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- --[[ not recommended
- -- Without epsilon
- function CE2F(a, b)
- -- less 1
- if (b < 1) then
- return a == b + math.floor(a)
- end
- -- Else
- return a + math.floor(a) == b + math.floor(a)
- end
- ]]
- --------------
- -- function --
- --------------
- -- With epsilon
- local function macheps()
- local e = 1.0
- while (1.0 + e / 2.0 > 1.0) do
- e = e / 2.0
- end
- return e
- end
- -- Get epsilon
- local double_epsilon = macheps()
- -- Main function for compare
- function math.double_compare(a, b)
- return a + double_epsilon == b + double_epsilon
- end
- -----------
- -- Tests --
- -----------
- -- Plus
- print(math.double_compare(1.12 + 1.11, 2.23)) --> true
- print(math.double_compare(100.5, 100 + 0.5)) --> true
- print(math.double_compare(0.080, 0.075 + 0.005)) --> true
- print(math.double_compare(-0.5 + 1, 0.5)) --> true
- -- Minus
- print(math.double_compare(99.9, 100 - 0.1)) --> true
- print(math.double_compare(12.375 - 0.375, 12)) --> true
- print(math.double_compare(0.012 - 0.002, 0.01)) --> true
- -- Multiply
- print(math.double_compare(2.5 * 2, 5)) --> true
- print(math.double_compare(4 * 0.5, 2)) --> true
- print(math.double_compare(0.75 * 10, 7.5)) --> true
- -- Div
- print(math.double_compare(5 / 0.5, 10)) --> true
- print(math.double_compare(1 / 100, 0.01)) --> true
- print(math.double_compare(5 / 100, 5 / 100)) --> true
- -- Brute
- local count = 99999
- for i = 1, count do
- -- print(0.01*i, 0.01*i)
- -- print(1/i, 1/i)
- -- print(0.01+i, 0.01+i)
- -- print(count-i, count-i)
- if not math.double_compare(0.01*i, 0.01*i) then
- print("FALSE MULT", i)
- end
- if not math.double_compare(1/i, 1/i) then
- print("FALSE DIV", i)
- end
- if not math.double_compare(0.01+i, 0.01+i) then
- print("FALSE PLUS", i)
- end
- if not math.double_compare(count-i, count-i) then
- print("FALSE MINUS", i)
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement