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