The math.fmod() is a library method of math module, it is used to find the modulus or given numbers, where the first parameter is a dividend and the second parameter is divisor. It accepts two arguments and returns modulus in float type.
Note: math.fmod() can be used to get the modules/remainder of positive and negative integers, positive and negative floats.
math.fmod(x,y)
x
, y
– numbers (positive or negative, integer or float).float
– it returns a float value, which is a remainder (modulus) of given numbers x
, y
.The fmod() function returns a floating-point number value after calculating the module of the given two numbers.
Please note that,
# import math library
import math
print(math.fmod(25,5))
print(math.fmod(20,3))
print(math.fmod(-20,12))
print(math.fmod(-13,6))
Output
0.0
2.0
-8.0
-1.0
Note that in output all the numbers whether they are negative or positive are converted into a floating point number after calculating module through fmod() in Python programming language.
Python code to demonstrate example of math.fmod() method
# app.py
# Importing math library
import math
# Demonstrating working of fmod()
# Using different values of x and y
# When both are positive
x = 12
y = 9
print("Module of ", x, " and ", y, "is: ", math.fmod(x, y))
# When any one of them are negative
x = -16
y = 3
print("Module of ", x, " and ", y, "is: ", math.fmod(x, y))
# When both are negative
x = -65
y = -31
print("Module of ", x, " and ", y, "is: ", math.fmod(x, y))
# When second argument (y) is 0
x = 10
y = 0
print("Module of ", x, " and ", y, "is: ", math.fmod(x, y))
Output
Module of 12 and 9 is: 3.0
Module of -16 and 3 is: -1.0
Module of -65 and -31 is: -3.0
Traceback (most recent call last):
File "fmod.py", line 24, in <module>
print("Module of ",x," and ",y, "is: ",math.fmod(x,y))
ValueError: math domain error
In the above code, we have declared two variables x and y and given their different values in different cases.
After that, we have a printed module of each case, we can see that the answer is positive only when both x and y are positive, and except that in all cases, the answer is negative.
Also, we can see that in each case, the answer is in floating-point.
However, in the last case, when we gave the value of y is 0, we got a ValueError.
Thanks for reading !
#python #programming