Modulo operator in Python

后端 未结 5 1932
無奈伤痛
無奈伤痛 2020-11-27 20:16

What does modulo in the following piece of code do?

from math import *
3.14 % 2 * pi

How do we calculate modulo on a floating point number?

5条回答
  •  無奈伤痛
    2020-11-27 20:30

    When you have the expression:

    a % b = c
    

    It really means there exists an integer n that makes c as small as possible, but non-negative.

    a - n*b = c
    

    By hand, you can just subtract 2 (or add 2 if your number is negative) over and over until the end result is the smallest positive number possible:

      3.14 % 2
    = 3.14 - 1 * 2
    = 1.14
    

    Also, 3.14 % 2 * pi is interpreted as (3.14 % 2) * pi. I'm not sure if you meant to write 3.14 % (2 * pi) (in either case, the algorithm is the same. Just subtract/add until the number is as small as possible).

提交回复
热议问题