Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

modulo of a number - python vs c#

Tags:

python

c#

Lets take the basic arithmetic operation - modulo

I get different outputs depending on different languages.

Python

>>> -1 % 12
11

C#

var res = -1 % 12;
output: res = -1

Why am I seeing such behaviour? Ideally I'd like the output to be 11 in both cases.

Also does anyone know if I can achieve this in C#?

like image 267
dopplesoldner Avatar asked Dec 02 '22 22:12

dopplesoldner


1 Answers

The premise of the question is incorrect. The % operator in C# is not the modulus operator, it is the remainder operator, while in Python it is a modulus operator.

As Eric Lippert Describes, modulus and remainder are the same for all positive numbers, but they handle negative numbers differently.

Despite both C# and Python having a % operator, doesn't mean they both represent a modulus.

It's worth noting that other languages, such as C++ and Java use remainder for the % operator, not modulus, which likely contributed to why C# choose to use remainder as well. Since there isn't a lot of consistency in what is meant by the % operator, I would suggest looking it up in the language docs whenever working with a new language.

like image 72
Servy Avatar answered Dec 09 '22 14:12

Servy