-1

I was just playing around with arithmetic operators in Python, when I encountered a strange thing of Python arithmetic.

>>> (11 / 1) % (2 / 11)
0.0909090909090906
>>> 11 / 1 % 2 / 11
0.09090909090909091

Why is there a difference in both these answers? The mathematics is the same, then why a difference in the result?

coderboy
  • 1,710
  • 1
  • 6
  • 16
  • 2
    This is like asking why `(1 + 2) * 3` gives other result than `1 + 2 * 3` – DeepSpace Mar 31 '21 at 17:54
  • @DeepSpace I guess this one is not that simple. I would appreciate if you could apply this same rule to the question above..... – coderboy Mar 31 '21 at 17:56
  • It is just as simple. Parenthesis change order of operation – DeepSpace Mar 31 '21 at 17:58
  • 1
    @coderboy Since `%` and divide `/` have the same precedence it is evaluated left to right. While in DeepSpaces example `*` has higher precedence than `+`. – Sash Sinha Mar 31 '21 at 17:58
  • Please repeat [on topic](https://stackoverflow.com/help/on-topic) and [how to ask](https://stackoverflow.com/help/how-to-ask) from the [intro tour](https://stackoverflow.com/tour). Stack Overflow is not intended to replace existing documentation and tutorials. We expect you to look up operator precedence; this is not a Stack Overflow issue. – Prune Mar 31 '21 at 18:03

1 Answers1

3

/ and % have the same operator precedence. So 11 / 1 % 2 / 11 is evaluated left-to-right, i.e. ((11 / 1) % 2) / 11.

0x5453
  • 12,753
  • 1
  • 32
  • 61