preface

This is my third article about getting started.

Python is known to be a dynamic, interpreted, strongly typed language. Js is a dynamic, interpreted, weakly typed language. There are many similarities and many differences between the two languages. This paper briefly introduces the problem of negative number mod.

Take more negative

I don’t know if you’ve ever seen negative number division or mod, but intuitively, mod of negative numbers doesn’t make any physical sense. Different programming languages have different rules on this issue.

Py Calculation results

Let’s look at the result of py running %.

7%3==1// Well, everybody is the same.

-7%3==2// emmmmmmmmmmmmmmmmmmm, is -7 repeated by 3, add to the positive number, exactly 2? .

-7%-3==-1

7%-3==-2 // what happened, keep repeating -3, less than 0 until -2?


Js calculation results

Take a look at the browser console JS running results

In the case of the same symbol, the result is the same as py, but the division and dividend are different!!

Analysis of the

In terms of form, the remainder in PY has the same sign as the divisor, while the result in JS has the same sign as the dividend.

These two differences, in fact, come from their different rules for division. Remainder = dividend – dividend/divisor x divisor. Because the quotient is different, the remainder is different.

There are two division modes:

  • Floor division, quotient is rounded by floor method, tends to negative infinity truncation. Python uses this.

In the example: -7%3, the quotient is -2.333333, rounded down to -3, so the modulus is -7 -(-3) x 3 => -7 -(-9)==2.

  • Truncate division, the quotient as close to 0 as possible. Most programming languages such as C, Java, and JS use this scheme.

-7%3, the quotient -2.333333 is rounded to -2, so the remainder is -7- (-6) ==-1.

Well, if you look at it this way, it makes perfect sense.

conclusion

In summary, PY is a maverick. Although this problem may not be encountered in production, it is still possible to understand.

If there are any mistakes, please correct them.