0

So my understanding of the modulus operator is that it returns the remainder of the division, after dividing the dividend with a divisor. and of course, this dividend and divisor could be either an integer(-ve and +ve) or a decimal number.

and then I discovered that this modulus operator works differently for java and python. ie. when dealing with negative numbers.

while python seems to assign the sign of denominator to its output. java seems to assign the sign of the numerator to its output. Fair enough, considering that they are two different languages they can have different rules.

but then I experimented with some values and discovered that they output different values for the same operands. ex -

Python -

print((-4.1)%2);# outputs : 1.9000000000000004

Java -

 public static void main(String[] args) {
        float f = -4.1f;
        float b = 2f;
        System.out.println(f%b); // outputs : -0.099999905
 }

After seeing the results, I just had to ask what's going on behind the scenes how are they working? and if there were to be a right answer, which one would it be?

kevin godfrey
  • 153
  • 1
  • 11
  • They are not the same operation. – Turing85 Jan 03 '22 at 14:00
  • Furthermore what is clearly defined in a mathematical point of view is the modulus of two strictly positive integers. As soon as you use floating point or negative numbers,, different libraries are allowed to use different definitions. – Serge Ballesta Jan 03 '22 at 14:06

0 Answers0