Python math.fmod() Method



The Python math.fmod() method is used to calculate the floating-point remainder of dividing one number by another. Mathematically, it calculates the remainder when dividing the first argument (dividend) by the second argument (divisor), where both arguments are floating-point numbers.

The formula to calculate the remainder using the fmod() method is −

fmod(x,y) = x − y × ⌊x/y⌋

Where, ⌊x/y⌋ denotes the largest integer less than or equal to x/y. For example, if you have x = 10.5 and y = 3.0, then math.fmod(10.5, 3.0) returns 10.5 − 3.0 × ⌊10.5/3.0⌋ = 1.5.

Syntax

Following is the basic syntax of the Python math.fmod() method −

math.fmod(x, y)

Parameters

This method accepts the following parameters −

  • x − This is a numeric value representing the numerator.

  • y − This is a numeric value representing the denominator.

Return Value

The method returns a float, which is the remainder of dividing x by y. The sign of the result is the same as the sign of x, regardless of the sign of y.

Example 1

In the following example, we are calculating the remainder of 10 divided by 3 using the math.fmod() method −

import math
result = math.fmod(10, 3)
print("The result obtained is:",result) 

Output

The output obtained is as follows −

The result obtained is: 1.0

Example 2

When a negative dividend is passed to the fmod() method, it returns a result with the same sign as the dividend.

Here, we are calculating the remainder of -10 divided by 3 using the math.fmod() method −

import math
result = math.fmod(-10, 3)
print("The result obtained is:",result) 

Output

Following is the output of the above code −

The result obtained is: -1.0

Example 3

If we pass floating-point numbers as both the dividend and divisor, the fmod() method returns a float value −

import math
result = math.fmod(7.5, 3.5)
print("The result obtained is:",result) 

Output

We get the output as shown below −

The result obtained is: 0.5

Example 4

When a negative divisor is passed to the fmod() method, it retains the sign of the dividend.

Now, we are calculating the remainder of 10 divided by -3 using the math.fmod() method −

import math
result = math.fmod(10, -3)
print("The result obtained is:",result) 

Output

The result produced is as shown below −

The result obtained is: 1.0
python_maths.htm
Advertisements