Does modulo work on floats python?

Actually, it's not true that 3.5 % 0.1 is 0.1. You can test this very easily:

>>> print[3.5 % 0.1]
0.1
>>> print[3.5 % 0.1 == 0.1]
False

In actuality, on most systems, 3.5 % 0.1 is 0.099999999999999811. But, on some versions of Python, str[0.099999999999999811] is 0.1:

>>> 3.5 % 0.1
0.099999999999999811
>>> repr[3.5 % 0.1]
'0.099999999999999811'
>>> str[3.5 % 0.1]
'0.1'

Now, you're probably wondering why 3.5 % 0.1 is 0.099999999999999811 instead of 0.0. That's because of the usual floating point rounding issues. If you haven't read What Every Computer Scientist Should Know About Floating-Point Arithmetic, you should—or at least the brief Wikipedia summary of this particular issue.

Note also that 3.5/0.1 is not 34, it's 35. So, 3.5/0.1 * 0.1 + 3.5%0.1 is 3.5999999999999996, which isn't even close to 3.5. This is pretty much fundamental to the definition of modulus, and it's wrong in Python, and just about every other programming language.

But Python 3 comes to the rescue there. Most people who know about // know that it's how you do "integer division" between integers, but don't realize that it's how you do modulus-compatible division between any types. 3.5//0.1 is 34.0, so 3.5//0.1 * 0.1 + 3.5%0.1 is [at least within a small rounding error of] 3.5. This has been backported to 2.x, so [depending on your exact version and platform] you may be able to rely on this. And, if not, you can use divmod[3.5, 0.1], which returns [within rounding error] [34.0, 0.09999999999999981] all the way back into the mists of time. Of course you still expected this to be [35.0, 0.0], not [34.0, almost-0.1], but you can't have that because of rounding errors.

If you're looking for a quick fix, consider using the Decimal type:

>>> from decimal import Decimal
>>> Decimal['3.5'] % Decimal['0.1']
Decimal['0.0']
>>> print[Decimal['3.5'] % Decimal['0.1']]
0.0
>>> [Decimal[7]/2] % [Decimal[1]/10]
Decimal['0.0']

This isn't a magical panacea — for example, you'll still have to deal with rounding error whenever the exact value of an operation isn't finitely representable in base 10 - but the rounding errors line up better with the cases human intuition expects to be problematic. [There are also advantages to Decimal over float in that you can specify explicit precisions, track significant digits, etc., and in that it's actually the same in all Python versions from 2.4 to 3.3, while details about float have changed twice in the same time. It's just that it's not perfect, because that would be impossible.] But when you know in advance that your numbers are all exactly representable in base 10, and they don't need more digits than the precision you've configured, it will work.

Python modulo operator [%] is used to get the remainder of a division. The modulo operation is supported for integers and floating point numbers.

The syntax of modulo operator is a % b. Here “a” is dividend and “b” is the divisor. The output is the remainder when a is divided by b.

If both “a” and “b” are integers, then the remainder is also an integer. If one of them is float, the result is also a floating point number.

Python Module Operator Example

Let’s look at some examples of modulo operator.

1. Modulo with integers

>>> 10 % 3 
1
>>> 2 % 2
0
>>> 

2. Modulo with float

>>> 9 % 3.0
0.0
>>> 10 % 3.0
1.0
>>> 

3. Modulo with user inputs

x = input["Please enter first number:\n"]
fx = float[x]

y = input["Please enter first number:\n"]
fy = float[y]

print[f'{x} % {y} = {fx % fy}']

Python Modulo Operator

When we get the user entered data, it’s in the form of string. We are using the float[] built-in function to convert them to floating point number. That’s why the remainder is 1.0 and not 1.

Recommended Read: Python input[] function

4. ZeroDivisionError Example

If the divisor is 0, the modulo operator will throw ZeroDivisionError. We can use try-except block to catch the error.

a = 10.5
b = 0

try:
    print[f'{a} % {b} = {a % b}']
except ZeroDivisionError as zde:
    print["We cannot divide by 0"]

Python Modulo ZeroDivisionError

5. Modulo with Negative Numbers

Python modulo operator always return the remainder having the same sign as the divisor. This can lead to some confusion with the output.

>>> -5 % 3
1
>>> 5 % -3
-1
>>> -10 % 3
2
>>> 

  • -5 % 3 = [1 -2*3] % 3 = 1
  • 5 % -3 = [-1 * -2*-3] % 3 = -1
  • -10 % 3 = [2 -4*3] % 3 = 2

6. Python Modulo math.fmod[]

The behavior of % operator with negative numbers is different from the platform C library. If you want the modulo operation to behave like C programming, you should use math module fmod[] function. This is the recommended function for getting modulo with floating point numbers.

>>> import math
>>> math.fmod[-5, 3]
-2.0
>>> math.fmod[5, -3]
2.0
>>> math.fmod[-10, 3]
-1.0
>>> 

  • fmod[-5, 3] = fmod[-2 -1*3, 3] = -2.0
  • fmod[5, -3] = fmod[2 -1*-3, -3] = 2.0
  • fmod[-10, 3] = fmod[-1 -3*3, 3] = -1.0

Overloading Modulo Operator

We can overload modulo operator by implementing __mod__[] function in our class definition.

class Data:

    def __init__[self, i]:
        self.id = i

    def __mod__[self, other]:
        print['modulo function called']
        return self.id % other.id

    def __str__[self]:
        return f'Data[{self.id}]'


d1 = Data[10]
d2 = Data[3]

print[f'{d1} % {d2} = {d1%d2}']

Output:

modulo function called
Data[10] % Data[3] = 1

Quick word on Floating Point Arithmetic Issues

We use binary format to store values in computers. When it comes to fractions, most of the times we can’t represent them exactly as binary fractions. For example, 1/3 can’t be represented in exact binary format and it will always be an approximate value.

That’s why you can get unexpected results when performing arithmetic operations with floating point numbers. It’s clear from the output of below modulo operations.

>>> 9.6 % 3.2
3.1999999999999993

The output should be 0 because 3.2*3 is 9.6. But, the float fraction values are not exactly represented and the approximation is causing this error. It’s clear from this example too.

>>> 9.6 == 3.2 * 3
False
>>> 

So, you should give extra care when working with floating point numbers. It’s advisable to perform a rounding and then only compare two floating point numbers.

>>> round[9.6, 3] == round[3.2 * 3, 3]
True

References:

  • Floating Point Arithmetic Issues
  • ZeroDivisionError
  • Python Operators
  • math.fmod[] API Doc

Can you use modulus with floats?

Yes, %[modulo] operator isn't work with floats and double.. if you want to do the modulo operation on large number you can check long long int[64bits] might this help you.

How do you find the modulus of a float number in Python?

Python modulo operator [%] is used to get the remainder of a division. The modulo operation is supported for integers and floating point numbers. The syntax of modulo operator is a % b .

Why modulus is not used in float?

Because C was designed to provide an efficient high-level programming environment to the PDP-11 and it didn't have a modulus instruction for floating point numbers.

Can you use modulo operator with float and int?

The modulo operator, like the other arithmetic operators, can be used with the numeric types int and float . As you'll see later on, it can also be used with other types like math. fmod[] , decimal.

Chủ Đề