mathutils.lua 974 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. --- Math utilities.
  2. -- @module advtrains_doc_integration.mathutils
  3. -- @alias M
  4. local M = {}
  5. local function gcdmain(x, y, ...)
  6. if y == nil then
  7. return x or 1
  8. end
  9. y = y%x
  10. if y == 0 then
  11. return gcdmain(x, ...)
  12. end
  13. return gcdmain(y, x, ...)
  14. end
  15. --- Compute the greatest common divider.
  16. -- Note that the behavior of this function is undefined if the arguments
  17. -- include infinity or NaN.
  18. -- @tparam integer ... The numbers used for the computation.
  19. -- @treturn integer The GCD of the given numbers.
  20. function M.gcd(...)
  21. local args = {...}
  22. for k, v in pairs(args) do
  23. if v == 0 then
  24. return 0
  25. elseif v ~= v then
  26. return v
  27. elseif v < 0 then
  28. args[k] = -v
  29. end
  30. end
  31. return gcdmain(unpack(args))
  32. end
  33. --- Reduce a fraction.
  34. -- @tparam integer num The numerator.
  35. -- @tparam integer denom The denominator.
  36. -- @treturn int,int The reduced fraction.
  37. function M.reduce_fraction(num, denom)
  38. local gcd = M.gcd(num, denom)
  39. return num/gcd, denom/gcd
  40. end
  41. return M