Advertisement
freswinn

GDScript: Smart Modulus

Feb 27th, 2023
1,497
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. func smart_mod(dividend, divisor, sided_toward_zero : bool = false):
  2.     # DECIMAL DIVIDEND, INTEGER DIVISOR
  3.     # smart_mod(4.7, 3) = 1.7
  4.    
  5.     # DECIMAL DIVIDEND, DECIMAL DIVISOR
  6.     # smart_mod(423.9, 7.49) = 11.95
  7.    
  8.     # NEGATIVE DIVIDEND
  9.     # smart_mod(-4.7, 3, false) = 1.3
  10.     # smart_mod(-4.7, 3, true) = -1.7
  11.    
  12.     var out : float
  13.     if divisor == 0:
  14.         printerr("Useful.gd, smart_mod  |  Attempted division by zero! Returning null")
  15.         return null
  16.     elif dividend == 0:
  17.         return 0
  18.     else:
  19.         var s = sign(dividend * divisor)
  20.         var num = abs(dividend)
  21.         var den = abs(divisor)
  22.         var quo = floor(num / den)
  23.         out = s * (num - (quo * den))
  24.         if !sided_toward_zero:
  25.             out += den
  26.             if out == num:
  27.                 out = 0
  28.     return out
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement