Python - fmod() function

PythonServer Side ProgrammingProgramming

the fmod()in python implements the math modulo operation. The remainder obtained after the division operation on two operands is known as modulo operation. It is a part of standard library under the math module. In the below examples we will see how the modulo operation gives different out puts under various scenarios.

Positive numbers

For positive numbers, the result is the remainder of the operation after the first integer is divided by the second. Interesting the result always comes as a float as we can see from the type of the result.

Example

 Live Demo

from math import fmod
print(fmod(6, 7))
print(type(fmod(6,7)))
print(fmod(0, 7))
print(fmod(83.70, 6.5))

Running the above code gives us the following result:

6.0
<type 'float'>
0.0
5.7

Negative Numbers

The negative numbers give the result with a negative sign except when the divisor is negative.

Example

print(fmod(29, -7))
print(fmod(-29, 7))
print(fmod(-29, -7))
print(fmod(-30, 8.98))

Running the above code gives us the following result:

1.0
-1.0
-1.0
-3.0599999999999987

Tuples and Lists

We can use the same logic in Tuples and Lists by referring to the individual elements in tuples and logics.

Example

 Live Demo

from math import fmod
Tuple = (25, 13, -7, -60 )
List = [-69, 58, -49, 36]
print("\nTuples: ")
print(fmod(Tuple[3], 7))
print(fmod(Tuple[1], -7))
print("Lists: ")
print(fmod(List[3], 6))
print(fmod(List[0], -25))

Running the above code gives us the following result:

Tuples:
-4.0
6.0
Lists:
0.0
-19.0
raja
Published on 30-Dec-2019 15:06:40
Advertisements