math.lua 749 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. --[[
  2. Math utils.
  3. --]]
  4. function math.hypot(x, y)
  5. return math.sqrt(x * x + y * y)
  6. end
  7. function math.sign(x, tolerance)
  8. tolerance = tolerance or 0
  9. if x > tolerance then
  10. return 1
  11. elseif x < -tolerance then
  12. return -1
  13. end
  14. return 0
  15. end
  16. function math.factorial(x)
  17. assert(x % 1 == 0 and x >= 0, "factorial expects a non-negative integer")
  18. if x >= 171 then
  19. -- 171! is greater than the biggest double, no need to calculate
  20. return math.huge
  21. end
  22. local v = 1
  23. for k = 2, x do
  24. v = v * k
  25. end
  26. return v
  27. end
  28. function math.round(x)
  29. if x < 0 then
  30. local int = math.ceil(x)
  31. local frac = x - int
  32. return int - ((frac <= -0.5) and 1 or 0)
  33. end
  34. local int = math.floor(x)
  35. local frac = x - int
  36. return int + ((frac >= 0.5) and 1 or 0)
  37. end