Jul 3, 2017 Replies: 4 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". In Python: Code: Copy print -1 % 24 # = 23 print -49 % 24 # = 23 In B4X (also Java and C): Code: Copy Log( -1 Mod 24) '= -1 Log(-49 Mod 24) '= -1 The trick: Code: Copy Sub PyMod(x As Double, y As Double) As Double Return (y + (x Mod y)) Mod y End Sub Enjoy. Last edited: Oct 4, 2017 Click to expand...
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". In Python: Code: Copy print -1 % 24 # = 23 print -49 % 24 # = 23 In B4X (also Java and C): Code: Copy Log( -1 Mod 24) '= -1 Log(-49 Mod 24) '= -1 The trick: Code: Copy Sub PyMod(x As Double, y As Double) As Double Return (y + (x Mod y)) Mod y End Sub Enjoy.
Erel B4X founder Staff member Licensed User Longtime User Jul 3, 2017 #2 You can simplify it a bit: Code: Copy Sub pyMod (x As Int, y As Int) As Int Return (y + x) Mod y End Sub I've also changed the types to Int so it will be supported by B4i. Last edited: Jul 3, 2017
You can simplify it a bit: Code: Copy Sub pyMod (x As Int, y As Int) As Int Return (y + x) Mod y End Sub I've also changed the types to Int so it will be supported by B4i.
Ed Brown Active Member Licensed User Longtime User Jul 3, 2017 #3 Erel said: Return (y + x) Mod y Click to expand... This will still result in -1 instead of 23 when x=-49 and y=24
Erel said: Return (y + x) Mod y Click to expand... This will still result in -1 instead of 23 when x=-49 and y=24
Erel B4X founder Staff member Licensed User Longtime User Jul 3, 2017 #4 You are correct... I was mistaken as I sometimes use this code with degrees where the input is limited to -360 - 360 and therefore it is enough to add 360.
You are correct... I was mistaken as I sometimes use this code with degrees where the input is limited to -360 - 360 and therefore it is enough to add 360.
Ed Brown Active Member Licensed User Longtime User Jul 3, 2017 #5 I thought similarly as you. This will return -23 where x < 0 and 23 where x > 0 (in cases where negative results are desirable) Code: Copy (y*x - x) Mod y
I thought similarly as you. This will return -23 where x < 0 and 23 where x > 0 (in cases where negative results are desirable) Code: Copy (y*x - x) Mod y