Advertisement
uriid1

Comparison of two fractional numbers LUA

Nov 19th, 2021 (edited)
1,479
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.92 KB | None | 0 0
  1. --[[ not recommended
  2. -- Without epsilon
  3. function CE2F(a, b)
  4.     -- less 1
  5.     if (b < 1) then
  6.         return a == b + math.floor(a)
  7.     end
  8.    
  9.     -- Else
  10.     return a + math.floor(a) == b + math.floor(a)
  11. end
  12. ]]
  13.  
  14. --------------
  15. -- function --
  16. --------------
  17. -- With epsilon
  18. local function macheps()
  19.     local e = 1.0
  20.  
  21.     while (1.0 + e / 2.0 > 1.0) do
  22.         e = e / 2.0
  23.     end
  24.     return e
  25. end
  26.  
  27. -- Get epsilon
  28. local double_epsilon = macheps()
  29.  
  30. -- Main function for compare
  31. function math.double_compare(a, b)
  32.     return a + double_epsilon == b + double_epsilon
  33. end
  34.  
  35. -----------
  36. -- Tests --
  37. -----------
  38. -- Plus
  39. print(math.double_compare(1.12 + 1.11, 2.23))    --> true
  40. print(math.double_compare(100.5, 100 + 0.5))     --> true
  41. print(math.double_compare(0.080, 0.075 + 0.005)) --> true
  42. print(math.double_compare(-0.5 + 1, 0.5))        --> true
  43.  
  44. -- Minus
  45. print(math.double_compare(99.9, 100 - 0.1))     --> true
  46. print(math.double_compare(12.375 - 0.375, 12))  --> true
  47. print(math.double_compare(0.012 - 0.002, 0.01)) --> true
  48.  
  49. -- Multiply
  50. print(math.double_compare(2.5 * 2, 5))      --> true
  51. print(math.double_compare(4 * 0.5, 2))      --> true
  52. print(math.double_compare(0.75 * 10, 7.5))  --> true
  53.  
  54. -- Div
  55. print(math.double_compare(5 / 0.5, 10))       --> true
  56. print(math.double_compare(1 / 100, 0.01))     --> true
  57. print(math.double_compare(5 / 100, 5 / 100))  --> true
  58.  
  59.  
  60. -- Brute
  61. local count = 99999
  62. for i = 1, count do
  63.     -- print(0.01*i, 0.01*i)
  64.     -- print(1/i, 1/i)
  65.     -- print(0.01+i, 0.01+i)
  66.     -- print(count-i, count-i)
  67.  
  68.     if not math.double_compare(0.01*i, 0.01*i) then
  69.         print("FALSE MULT", i)
  70.     end
  71.     if not math.double_compare(1/i, 1/i) then
  72.         print("FALSE DIV", i)
  73.     end
  74.     if not math.double_compare(0.01+i, 0.01+i) then
  75.         print("FALSE PLUS", i)
  76.     end
  77.     if not math.double_compare(count-i, count-i) then
  78.         print("FALSE MINUS", i)
  79.     end
  80. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement