Does the modulo operator work with floating point numbers?


In this exercise, the modulo operator is used with only integer numbers. Will it work with floating point numbers too?


Yes, the Python modulo operator will work with floating point numbers.

>>> from math import pi
>>> def is_float(n):
    return n % 1 and True or False

>>> is_float(1)
>>> is_float(pi)

What this mean “return n % 1 and True or False”

This will take precedence, so will be either zero or a float.

Zero and True is False.

A float and True is True.

OR False will only happen when n % 1 is zero.

Hi, can you please elaborate on that? What does it mean “Zero and True is False” “A float and True is True” Thnx a lot!

Zero is the integer equivalent of False.

False and True == False

False short-circuits AND, and True short-circuits OR.

Modulo for floating point numbers does work, but there are some anomilies as shown by running the following program…

Write your remainder function here:

def remainder(num1,num2):
return 2 * num1 % (0.5 * num2)

Uncomment these function calls to test your remainder function:

print(remainder(15.4, 14.3))

should print 2.2 but gives 2.1999999999999993 instead!

print(remainder(9, 6))

should print 0

The above behavior is expected as Python 3 float operations yield a float.

Floating point arithmetic is not as exact as one might expect. The math is fairly complex and can often result in a very tiny error.


>>> 15.4 % 1

I would like to point out a correction. The following line is true only for non-zero floating-point numbers.

A float and True is True.

The function “is_float(n)” would fail to classify some floating-point numbers that produce 0.0 upon ‘n%1’ operation.

>>> 5.0%1
>>> 5.0%1 and True or False
1 Like