Re:Python, unlike C, has the mod operator always return a po...
by ollien on Wednesday December 29, 2021 @05:22PM
(#29730859)
Yep. I remember that for my first C assignment in college we had to write a calendar, and leap year calculations needed modulos. I remember distinctly that I tore my hair out trying to figure this out, especially because I was prototyping my math in Python. I eventually resolved that I needed to constantly ensure my sum was > 0 (by adding my modulo base).
[ Parent
| on HN ]
Re:Python, unlike C, has the mod operator always return a po...
by Normal_gaussian on Wednesday December 29, 2021 @05:37PM
(#29731024)
That will only work for cases where a >= -b. For the more general case:
> a mod b = ((a % b) + b) % b
The first remainder bounds it to -b < x < b. Then adding b goes to 0 < x < 2b. Then the second remainder gets th desired 0 <= x < b.
This will not work for b > max_int / 2 (solution in that case is much mkre language dependent)
Re:Python, unlike C, has the mod operator always return a po...
by yaur on Thursday December 30, 2021 @05:29AM
(#29735505)
What's the case where the C % operator behaves in an unexpected way? I've been wiring software for about 20 years and can count zero hands the number of times someone I've worked with has had to worry about how the modulo operator behaves with negative numbers.
Re:Python, unlike C, has the mod operator always return a po...
by housecarpenter on Thursday December 30, 2021 @06:09AM
(#29735722)
An example would be if you want to find the month corresponding to a timestamp. The obvious thing to do is to scale the timestamp so that it gives you the number of months after the epoch, take that number % 12, and map 0 to January, 1 to February, etc. (assuming the epoch is in January). But if you try to do that with a timestamp from before the epoch, you'll end up with 0 for January, -11 for February, -10 for March, etc.