Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modulo operator in Python

What does modulo in the following piece of code do?

from math import * 3.14 % 2 * pi 

How do we calculate modulo on a floating point number?

like image 480
KodeWarrior Avatar asked Oct 05 '12 22:10

KodeWarrior


People also ask

What is modulo operator example?

The modulus operator (also informally known as the remainder operator) is an operator that returns the remainder after doing an integer division. For example, 7 / 4 = 1 remainder 3. Therefore, 7 % 4 = 3. As another example, 25 / 7 = 3 remainder 4, thus 25 % 7 = 4.

What is modulus operator?

The modulus operator is added in the arithmetic operators in C, and it works between two available operands. It divides the given numerator by the denominator to find a result. In simpler words, it produces a remainder for the integer division. Thus, the remainder is also always an integer number only.


2 Answers

When you have the expression:

a % b = c 

It really means there exists an integer n that makes c as small as possible, but non-negative.

a - n*b = c 

By hand, you can just subtract 2 (or add 2 if your number is negative) over and over until the end result is the smallest positive number possible:

  3.14 % 2 = 3.14 - 1 * 2 = 1.14 

Also, 3.14 % 2 * pi is interpreted as (3.14 % 2) * pi. I'm not sure if you meant to write 3.14 % (2 * pi) (in either case, the algorithm is the same. Just subtract/add until the number is as small as possible).

like image 126
Blender Avatar answered Sep 22 '22 17:09

Blender


In addition to the other answers, the fmod documentation has some interesting things to say on the subject:

math.fmod(x, y)

Return fmod(x, y), as defined by the platform C library. Note that the Python expression x % y may not return the same result. The intent of the C standard is that fmod(x, y) be exactly (mathematically; to infinite precision) equal to x - n*y for some integer n such that the result has the same sign as x and magnitude less than abs(y). Python’s x % y returns a result with the sign of y instead, and may not be exactly computable for float arguments. For example, fmod(-1e-100, 1e100) is -1e-100, but the result of Python’s -1e-100 % 1e100 is 1e100-1e-100, which cannot be represented exactly as a float, and rounds to the surprising 1e100. For this reason, function fmod() is generally preferred when working with floats, while Python’s x % y is preferred when working with integers.

like image 27
Thomas Avatar answered Sep 20 '22 17:09

Thomas