Modulo operator in Python

后端 未结 5 1964
無奈伤痛
無奈伤痛 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:34

    you should use fmod(a,b)

    While abs(x%y) < abs(y) is true mathematically, for floats it may not be true numerically due to roundoff.

    For example, and assuming a platform on which a Python float is an IEEE 754 double-precision number, in order that -1e-100 % 1e100 have the same sign as 1e100, the computed result is -1e-100 + 1e100, which is numerically exactly equal to 1e100.

    Function fmod() in the math module returns a result whose sign matches the sign of the first argument instead, and so returns -1e-100 in this case. Which approach is more appropriate depends on the application.

    where x = a%b is used for integer modulo

提交回复
热议问题