fmod(x,y)
Return value is modulus of two input numbers with sign of x. Data type of return value is float. print(math.fmod(10,2)) # 0.0
print(math.fmod(10,3)) # 1.0
print(math.fmod(10,4)) # 2.0
Output will carry sign of x
print(math.fmod(10,-2)) # 0.0
print(math.fmod(10,-3)) # 1.0
print(math.fmod(10,4)) # 2.0
print(math.fmod(-10,4)) # -2.0
x is float here
print(math.fmod(10.34,4)) # 2.34
print(math.fmod(10,0)) # ValueError: math domain error
Using for loop
for i in range(0,10):
print("fmod(",i,",2) = ",math.fmod(i,2))
Output
fmod( 0 ,2) = 0.0
fmod( 1 ,2) = 1.0
fmod( 2 ,2) = 0.0
fmod( 3 ,2) = 1.0
fmod( 4 ,2) = 0.0
fmod( 5 ,2) = 1.0
fmod( 6 ,2) = 0.0
fmod( 7 ,2) = 1.0
fmod( 8 ,2) = 0.0
fmod( 9 ,2) = 1.0
fmod() is generally preferred when working with floats ( data type ) , while Python’s x % y is preferred when working with integers.
import math
x=-25
y=3
print(math.fmod(x,y)) # output -1.0
print(x % y) # output 2
Example 2
import math
x=25
y=-3
print(math.fmod(x,y)) # output 1.0
print(x % y) # output -2
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.