Python math.fmod() Method

Python math.fmod() method “returns the remainder (modulo) of x/y”.

Syntax

math.fmod(x,y)

Parameters

The math.fmod() function takes two arguments: x and y (both positive or negative), which find x%y.

Return Value

After calculating the module of the given two numbers, the fmod() function returns a floating-point number value.

  1. If x and y are both zero, math.fmod() method returns a ValueError.
  2. If the second argument means y is zero, it returns a ValueError.
  3. If any of x or y is not a number, this function returns a TypeError.

Time Complexity: O(1)

Auxiliary Space: O(1)

Example 1: How to Use math.fmod() Method

import math

# 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

ValueError: math domain error

Example 2: Using math.fmod() method tuples and lists

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

import math

Tuple = (21, 19, -11, -46)
List = [-69, 10, -48, 30]
print("\nTuples: ")

print(math.fmod(Tuple[3], 7))
print(math.fmod(Tuple[1], -7))

print("Lists: ")
print(math.fmod(List[3], 6))
print(math.fmod(List[0], -25))

Output

Tuples:
-4.0
5.0
Lists:
0.0
-19.0

Example 3: ValueError and TypeError

import math

print(math.fmod(0, 0))
print(math.fmod(21, 0))

print(math.fmod('3', 3))

Output

ValueError: math domain error

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.