Android Code Snippet PyMod() - Python Modulo

In Python, the modulo (%) of a negative number is calculated differently providing us a more useful result for real-life applications.

For example, imagine a clock on the wall, it reads "July 4th 2017, 00:30".
- If you set it back one hour, it becomes "July 3rd 2017, 23:30".
- If you set it back 49 hours, it becomes "July 1st 2017, 23:30".

84ea75944e23ae4e275ba5a9e0ecaee1.jpg


In Python:
B4X:
print  -1 % 24 # = 23
print -49 % 24 # = 23

In B4X (also Java and C):
B4X:
Log( -1 Mod 24) '= -1
Log(-49 Mod 24) '= -1

The trick:
B4X:
Sub PyMod(x As Double, y As Double) As Double
    Return (y + (x Mod y)) Mod y
End Sub

Enjoy. :)
 
Last edited:

Ed Brown

Active Member
Licensed User
Longtime User
I thought similarly as you. ;)

This will return -23 where x < 0 and 23 where x > 0 (in cases where negative results are desirable)
B4X:
(y*x - x) Mod y
 
Top