This question already has answers here:
How does the modulo (%) operator work on negative numbers in Python?
(12 answers)
Closed last month.
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?
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).
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.
Same thing you'd expect from normal modulo .. e.g. 7 % 4 = 3, 7.3 % 4.0 = 3.3
Beware of floating point accuracy issues.
same as a normal modulo 3.14 % 6.28 = 3.14, just like 3.14%4 =3.14 3.14%2 = 1.14 (the remainder...)
you should use fmod(a,b)
While abs(x%y) < abs(y) is true mathematically, for floats it may not be true numerically due to roundoff.
For example, and assuming a platform on which a Python float is an IEEE 754 double-precision number, in order that -1e-100 % 1e100 have the same sign as 1e100, the computed result is -1e-100 + 1e100, which is numerically exactly equal to 1e100.
Function fmod() in the math module returns a result whose sign matches the sign of the first argument instead, and so returns -1e-100 in this case. Which approach is more appropriate depends on the application.
where x = a%b is used for integer modulo
Related
The pow() function in python3 provide the values for exponents.
>>>pow(2,3)
8
Python3 has support to negative exponents that is can be represented using pow(10,-1). When I calculated pow(4,-1,5), it gave the output 4.
>>> pow(4, -1, 5)
4
I couldn't understand how the value 4 was calculated because, in the background, it performs
and it didn't return a value 4 as a reminder when I calculated manually.
When -ve value is passed in two values it responds with the desired output as a manual method.
>>> pow(4, -1)
.25
What is the difference when calculating a negative exponent with a modulus?
From the documentation;
If mod is present and exp is negative, base must be relatively prime to mod. In that case, pow(inv_base, -exp, mod) is returned, where inv_base is an inverse to base modulo mod.
Starting in python 3.8, the pow function allows you to calculate a modular inverse. As other answers have mentioned, this occurs when you use integers, have a negative exp, and base is relatively prime to mod. (this is the case in your example)
What is a modular inverse?
Lets start with normal inverses. Some number Y has an inverse X such that Y * X == 1. Modular inverses are very similar. For some number Y and some modulus mod, there exists an inverse X such that ((X * Y) % mod) == 1. From your example, you will see (4 * 4) % 5 does in fact equal 1, making 4 a valid modular inverse for Y = 4 and mod = 5.
How do you just get pow(4, -1, 5) == 0.25
Well, you could write it as separate steps (4 ** -1) % 5, but as the documentation says
if mod is present, return base to the power exp, modulo mod (computed more efficiently than pow(base, exp) % mod)
So you may sacrifice performance by using (4 ** -1) % 5. Unfortunately, it does not seem possible to do with pow.
I've been writing some code to list the Gaussian integer divisors of rational integers in Python. (Relating to Project Euler problem 153)
I seem to have reached some trouble with certain numbers and I believe it's to do with Python approximating the division of complex numbers.
Here is my code for the function:
def IsGaussian(z):
#returns True if the complex number is a Gaussian integer
return complex(int(z.real), int(z.imag)) == z
def Divisors(n):
divisors = []
#Firstly, append the rational integer divisors
for x in range(1, int(n / 2 + 1)):
if n % x == 0:
divisors.append(x)
#Secondly, two for loops are used to append the complex Guassian integer divisors
for x in range(1, int(n / 2 + 1)):
for y in range(1, int(n / 2 + 1)):
if IsGaussian(n / complex(x, y)) == n:
divisors.append(complex(x, y))
divisors.append(complex(x, -y))
divisors.append(n)
return divisors
When I run Divisors(29) I get [1, 29], but this is missing out four other divisors, one of which being (5 + 2j), which can clearly be seen to divide into 29.
On running 29 / complex(5, 2), Python gives (5 - 2.0000000000000004j)
This result is incorrect, as it should be (5 - 2j). Is there any way to somehow bypass Python's approximation? And why is it that this problem has not risen for many other rational integers under 100?
Thanks in advance for your help.
Internally, CPython uses a pair of double-precision floats for complex numbers. The behavior of numerical solutions in general is too complicated to summarize here, but some error is unavoidable in numerical calculations.
EG:
>>>print(.3/3)
0.09999999999999999
As such, it is often correct to use approximate equality rather than actual equality when testing solutions of this kind.
The isclose function in the cmath module is available for this exact reason.
>>>print(.3/3 == .1)
False
>>>print(isclose(.3/3, .1))
True
This kind of question is the domain of Numerical Analysis; this may be a useful tag for further questions on this subject.
Note that it is considered 'pythonic' for function identifiers to be in snake_case.
from cmath import isclose
def is_gaussian(z):
#returns True if the complex number is a Gaussian integer
rounded = complex(round(z.real), round(z.imag))
return isclose(rounded, z)
You could define an epsilon, by using round to round to the desired number of decimal places/precision (e.g. 10):
def IsGaussian(z, prec=10):
# returns True if the complex number is a Gaussian integer
# rounds the input number to the `prec` number of digits
z = complex(round(z.real,prec), round(z.imag,prec))
return complex(int(z.real), int(z.imag)) == z
Your code has another issue though:
if IsGaussian(n / complex(x, y)) == n:
This will only give results for n = 0 or n = 1. You probably want to remove the check for equality.
I was researching some information on the topic of trial division, and I came across this symbol in Python:
//=
I got this from here where the code in the example says:
n //= p
I can't tell what this is supposed to mean, and my research continues to bring poor results in terms of webpages.
// is integer division and the
n //= p
syntax is short for
n = n // p
except the value n is modified directly if it supports this.
When you see an operator followed by an =, that is performing the operation and then assigning it into the variable. For example, x += 2 means x = x + 2 or add 2 to x.
The // operator specifically does integer devision instead of floating point division. For example, 5 // 4 gives you 1, while 5 / 4 gives you 1.25 (in Python 3).
Therefore, x //= 3 means divide x by 3 (in an integer division fashion), and store the value back into x. It is equivalent to x = x // 3
// is the floor division operator, therefore //= is simply the inplace floor division operator.
In Python 3, I am checking whether a given value is triangular, that is, it can be represented as n * (n + 1) / 2 for some positive integer n.
Can I just write:
import math
def is_triangular1(x):
num = (1 / 2) * (math.sqrt(8 * x + 1) - 1)
return int(num) == num
Or do I need to do check within a tolerance instead?
epsilon = 0.000000000001
def is_triangular2(x):
num = (1 / 2) * (math.sqrt(8 * x + 1) - 1)
return abs(int(num) - num) < epsilon
I checked that both of the functions return same results for x up to 1,000,000. But I am not sure if generally speaking int(x) == x will always correctly determine whether a number is integer, because of the cases when for example 5 is represented as 4.99999999999997 etc.
As far as I know, the second way is the correct one if I do it in C, but I am not sure about Python 3.
There is is_integer function in python float type:
>>> float(1.0).is_integer()
True
>>> float(1.001).is_integer()
False
>>>
Both your implementations have problems. It actually can happen that you end up with something like 4.999999999999997, so using int() is not an option.
I'd go for a completely different approach: First assume that your number is triangular, and compute what n would be in that case. In that first step, you can round generously, since it's only necessary to get the result right if the number actually is triangular. Next, compute n * (n + 1) / 2 for this n, and compare the result to x. Now, you are comparing two integers, so there are no inaccuracies left.
The computation of n can be simplified by expanding
(1/2) * (math.sqrt(8*x+1)-1) = math.sqrt(2 * x + 0.25) - 0.5
and utilizing that
round(y - 0.5) = int(y)
for positive y.
def is_triangular(x):
n = int(math.sqrt(2 * x))
return x == n * (n + 1) / 2
You'll want to do the latter. In Programming in Python 3 the following example is given as the most accurate way to compare
def equal_float(a, b):
#return abs(a - b) <= sys.float_info.epsilon
return abs(a - b) <= chosen_value #see edit below for more info
Also, since epsilon is the "smallest difference the machine can distinguish between two floating-point numbers", you'll want to use <= in your function.
Edit: After reading the comments below I have looked back at the book and it specifically says "Here is a simple function for comparing floats for equality to the limit of the machines accuracy". I believe this was just an example for comparing floats to extreme precision but the fact that error is introduced with many float calculations this should rarely if ever be used. I characterized it as the "most accurate" way to compare in my answer, which in some sense is true, but rarely what is intended when comparing floats or integers to floats. Choosing a value (ex: 0.00000000001) based on the "problem domain" of the function instead of using sys.float_info.epsilon is the correct approach.
Thanks to S.Lott and Sven Marnach for their corrections, and I apologize if I led anyone down the wrong path.
Python does have a Decimal class (in the decimal module), which you could use to avoid the imprecision of floats.
floats can exactly represent all integers in their range - floating-point equality is only tricky if you care about the bit after the point. So, as long as all of the calculations in your formula return whole numbers for the cases you're interested in, int(num) == num is perfectly safe.
So, we need to prove that for any triangular number, every piece of maths you do can be done with integer arithmetic (and anything coming out as a non-integer must imply that x is not triangular):
To start with, we can assume that x must be an integer - this is required in the definition of 'triangular number'.
This being the case, 8*x + 1 will also be an integer, since the integers are closed under + and * .
math.sqrt() returns float; but if x is triangular, then the square root will be a whole number - ie, again exactly represented.
So, for all x that should return true in your functions, int(num) == num will be true, and so your istriangular1 will always work. The only sticking point, as mentioned in the comments to the question, is that Python 2 by default does integer division in the same way as C - int/int => int, truncating if the result can't be represented exactly as an int. So, 1/2 == 0. This is fixed in Python 3, or by having the line
from __future__ import division
near the top of your code.
I think the module decimal is what you need
You can round your number to e.g. 14 decimal places or less:
>>> round(4.999999999999997, 14)
5.0
PS: double precision is about 15 decimal places
It is hard to argue with standards.
In C99 and POSIX, the standard for rounding a float to an int is defined by nearbyint() The important concept is the direction of rounding and the locale specific rounding convention.
Assuming the convention is common rounding, this is the same as the C99 convention in Python:
#!/usr/bin/python
import math
infinity = math.ldexp(1.0, 1023) * 2
def nearbyint(x):
"""returns the nearest int as the C99 standard would"""
# handle NaN
if x!=x:
return x
if x >= infinity:
return infinity
if x <= -infinity:
return -infinity
if x==0.0:
return x
return math.floor(x + 0.5)
If you want more control over rounding, consider using the Decimal module and choose the rounding convention you wish to employ. You may want to use Banker's Rounding for example.
Once you have decided on the convention, round to an int and compare to the other int.
Consider using NumPy, they take care of everything under the hood.
import numpy as np
result_bool = np.isclose(float1, float2)
Python has unlimited integer precision, but only 53 bits of float precision. When you square a number, you double the number of bits it requires. This means that the ULP of the original number is (approximately) twice the ULP of the square root.
You start running into issues with numbers around 50 bits or so, because the difference between the fractional representation of an irrational root and the nearest integer can be smaller than the ULP. Even in this case, checking if you are within tolerance will do more harm than good (by increasing the number of false positives).
For example:
>>> x = (1 << 26) - 1
>>> (math.sqrt(x**2)).is_integer()
True
>>> (math.sqrt(x**2 + 1)).is_integer()
False
>>> (math.sqrt(x**2 - 1)).is_integer()
False
>>> y = (1 << 27) - 1
>>> (math.sqrt(y**2)).is_integer()
True
>>> (math.sqrt(y**2 + 1)).is_integer()
True
>>> (math.sqrt(y**2 - 1)).is_integer()
True
>>> (math.sqrt(y**2 + 2)).is_integer()
False
>>> (math.sqrt(y**2 - 2)).is_integer()
True
>>> (math.sqrt(y**2 - 3)).is_integer()
False
You can therefore rework the formulation of your problem slightly. If an integer x is a triangular number, there exists an integer n such that x = n * (n + 1) // 2. The resulting quadratic is n**2 + n - 2 * x = 0. All you need to know is if the discriminant 1 + 8 * x is a perfect square. You can compute the integer square root of an integer using math.isqrt starting with python 3.8. Prior to that, you could use one of the algorithms from Wikipedia, implemented on SO here.
You can therefore stay entirely in python's infinite-precision integer domain with the following one-liner:
def is_triangular(x):
return math.isqrt(k := 8 * x + 1)**2 == k
Now you can do something like this:
>>> x = 58686775177009424410876674976531835606028390913650409380075
>>> math.isqrt(k := 8 * x + 1)**2 == k
True
>>> math.isqrt(k := 8 * (x + 1) + 1)**2 == k
False
>>> math.sqrt(k := 8 * x + 1)**2 == k
False
The first result is correct: x in this example is a triangular number computed with n = 342598234604352345342958762349.
Python still uses the same floating point representation and operations C does, so the second one is the correct way.
Under the hood, Python's float type is a C double.
The most robust way would be to get the nearest integer to num, then test if that integers satisfies the property you're after:
import math
def is_triangular1(x):
num = (1/2) * (math.sqrt(8*x+1)-1 )
inum = int(round(num))
return inum*(inum+1) == 2*x # This line uses only integer arithmetic
What does the % in a calculation? I can't seem to work out what it does.
Does it work out a percent of the calculation for example: 4 % 2 is apparently equal to 0. How?
The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. The arguments may be floating point numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4*0.7 + 0.34.) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand [2].
Taken from http://docs.python.org/reference/expressions.html
Example 1:
6%2 evaluates to 0 because there's no remainder if 6 is divided by 2 ( 3 times ).
Example 2: 7%2 evaluates to 1 because there's a remainder of 1 when 7 is divided by 2 ( 3 times ).
So to summarise that, it returns the remainder of a division operation, or 0 if there is no remainder. So 6%2 means find the remainder of 6 divided by 2.
Somewhat off topic, the % is also used in string formatting operations like %= to substitute values into a string:
>>> x = 'abc_%(key)s_'
>>> x %= {'key':'value'}
>>> x
'abc_value_'
Again, off topic, but it seems to be a little documented feature which took me awhile to track down, and I thought it was related to Pythons modulo calculation for which this SO page ranks highly.
An expression like x % y evaluates to the remainder of x ÷ y - well, technically it is "modulus" instead of "reminder" so results may be different if you are comparing with other languages where % is the remainder operator. There are some subtle differences (if you are interested in the practical consequences see also "Why Python's Integer Division Floors" bellow).
Precedence is the same as operators / (division) and * (multiplication).
>>> 9 / 2
4
>>> 9 % 2
1
9 divided by 2 is equal to 4.
4 times 2 is 8
9 minus 8 is 1 - the remainder.
Python gotcha: depending on the Python version you are using, % is also the (deprecated) string interpolation operator, so watch out if you are coming from a language with automatic type casting (like PHP or JS) where an expression like '12' % 2 + 3 is legal: in Python it will result in TypeError: not all arguments converted during string formatting which probably will be pretty confusing for you.
[update for Python 3]
User n00p comments:
9/2 is 4.5 in python. You have to do integer division like so: 9//2 if you want python to tell you how many whole objects is left after division(4).
To be precise, integer division used to be the default in Python 2 (mind you, this answer is older than my boy who is already in school and at the time 2.x were mainstream):
$ python2.7
Python 2.7.10 (default, Oct 6 2017, 22:29:07)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 9 / 2
4
>>> 9 // 2
4
>>> 9 % 2
1
In modern Python 9 / 2 results 4.5 indeed:
$ python3.6
Python 3.6.1 (default, Apr 27 2017, 00:15:59)
[GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.42)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 9 / 2
4.5
>>> 9 // 2
4
>>> 9 % 2
1
[update]
User dahiya_boy asked in the comment session:
Q. Can you please explain why -11 % 5 = 4 - dahiya_boy
This is weird, right? If you try this in JavaScript:
> -11 % 5
-1
This is because in JavaScript % is the "remainder" operator while in Python it is the "modulus" (clock math) operator.
You can get the explanation directly from GvR:
Edit - dahiya_boy
In Java and iOS -11 % 5 = -1 whereas in python and ruby -11 % 5 = 4.
Well half of the reason is explained by the Paulo Scardine, and rest of the explanation is below here
In Java and iOS, % gives the remainder that means if you divide 11 % 5 gives Quotient = 2 and remainder = 1 and -11 % 5 gives Quotient = -2 and remainder = -1.
Sample code in swift iOS.
But when we talk about in python its gives clock modulus. And its work with below formula
mod(a,n) = a - {n * Floor(a/n)}
Thats means,
mod(11,5) = 11 - {5 * Floor(11/5)} => 11 - {5 * 2}
So, mod(11,5) = 1
And
mod(-11,5) = -11 - 5 * Floor(-11/5) => -11 - {5 * (-3)}
So, mod(-11,5) = 4
Sample code in python 3.0.
Why Python's Integer Division Floors
I was asked (again) today to explain why integer division in Python returns the floor of the result instead of truncating towards zero like C.
For positive numbers, there's no surprise:
>>> 5//2
2
But if one of the operands is negative, the result is floored, i.e., rounded away from zero (towards negative infinity):
>>> -5//2
-3
>>> 5//-2
-3
This disturbs some people, but there is a good mathematical reason. The integer division operation (//) and its sibling, the modulo operation (%), go together and satisfy a nice mathematical relationship (all variables are integers):
a/b = q with remainder r
such that
b*q + r = a and 0 <= r < b
(assuming a and b are >= 0).
If you want the relationship to extend for negative a (keeping b positive), you have two choices: if you truncate q towards zero, r will become negative, so that the invariant changes to 0 <= abs(r) < otherwise, you can floor q towards negative infinity, and the invariant remains 0 <= r < b. [update: fixed this para]
In mathematical number theory, mathematicians always prefer the latter choice (see e.g. Wikipedia). For Python, I made the same choice because there are some interesting applications of the modulo operation where the sign of a is uninteresting. Consider taking a POSIX timestamp (seconds since the start of 1970) and turning it into the time of day. Since there are 24*3600 = 86400 seconds in a day, this calculation is simply t % 86400. But if we were to express times before 1970 using negative numbers, the "truncate towards zero" rule would give a meaningless result! Using the floor rule it all works out fine.
Other applications I've thought of are computations of pixel positions in computer graphics. I'm sure there are more.
For negative b, by the way, everything just flips, and the invariant becomes:
0 >= r > b.
So why doesn't C do it this way? Probably the hardware didn't do this at the time C was designed. And the hardware probably didn't do it this way because in the oldest hardware, negative numbers were represented as "sign + magnitude" rather than the two's complement representation used these days (at least for integers). My first computer was a Control Data mainframe and it used one's complement for integers as well as floats. A pattern of 60 ones meant negative zero!
Tim Peters, who knows where all Python's floating point skeletons are buried, has expressed some worry about my desire to extend these rules to floating point modulo. He's probably right; the truncate-towards-negative-infinity rule can cause precision loss for x%1.0 when x is a very small negative number. But that's not enough for me to break integer modulo, and // is tightly coupled to that.
PS. Note that I am using // instead of / -- this is Python 3 syntax, and also allowed in Python 2 to emphasize that you know you are invoking integer division. The / operator in Python 2 is ambiguous, since it returns a different result for two integer operands than for an int and a float or two floats. But that's a totally separate story; see PEP 238.
Posted by Guido van Rossum at 9:49 AM
The modulus is a mathematical operation, sometimes described as "clock arithmetic." I find that describing it as simply a remainder is misleading and confusing because it masks the real reason it is used so much in computer science. It really is used to wrap around cycles.
Think of a clock: Suppose you look at a clock in "military" time, where the range of times goes from 0:00 - 23.59. Now if you wanted something to happen every day at midnight, you would want the current time mod 24 to be zero:
if (hour % 24 == 0):
You can think of all hours in history wrapping around a circle of 24 hours over and over and the current hour of the day is that infinitely long number mod 24. It is a much more profound concept than just a remainder, it is a mathematical way to deal with cycles and it is very important in computer science. It is also used to wrap around arrays, allowing you to increase the index and use the modulus to wrap back to the beginning after you reach the end of the array.
Python - Basic Operators
http://www.tutorialspoint.com/python/python_basic_operators.htm
Modulus - Divides left hand operand by right hand operand and returns remainder
a = 10 and b = 20
b % a = 0
In most languages % is used for modulus. Python is no exception.
% Modulo operator can be also used for printing strings (Just like in C) as defined on Google https://developers.google.com/edu/python/strings.
# % operator
text = "%d little pigs come out or I'll %s and %s and %s" % (3, 'huff', 'puff', 'blow down')
This seems to bit off topic but It will certainly help someone.
Also, there is a useful built-in function called divmod:
divmod(a, b)
Take two (non complex) numbers as arguments and return a pair of numbers
consisting of their quotient and
remainder when using long division.
x % y calculates the remainder of the division x divided by y where the quotient is an integer. The remainder has the sign of y.
On Python 3 the calculation yields 6.75; this is because the / does a true division, not integer division like (by default) on Python 2. On Python 2 1 / 4 gives 0, as the result is rounded down.
The integer division can be done on Python 3 too, with // operator, thus to get the 7 as a result, you can execute:
3 + 2 + 1 - 5 + 4 % 2 - 1 // 4 + 6
Also, you can get the Python style division on Python 2, by just adding the line
from __future__ import division
as the first source code line in each source file.
Modulus operator, it is used for remainder division on integers, typically, but in Python can be used for floating point numbers.
http://docs.python.org/reference/expressions.html
The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. The arguments may be floating point numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4*0.7 + 0.34.) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand [2].
It's a modulo operation, except when it's an old-fashioned C-style string formatting operator, not a modulo operation. See here for details. You'll see a lot of this in existing code.
It was hard for me to readily find specific use cases for the use of % online ,e.g. why does doing fractional modulus division or negative modulus division result in the answer that it does. Hope this helps clarify questions like this:
Modulus Division In General:
Modulus division returns the remainder of a mathematical division operation. It is does it as follows:
Say we have a dividend of 5 and divisor of 2, the following division operation would be (equated to x):
dividend = 5
divisor = 2
x = 5/2
The first step in the modulus calculation is to conduct integer division:
x_int = 5 // 2 ( integer division in python uses double slash)
x_int = 2
Next, the output of x_int is multiplied by the divisor:
x_mult = x_int * divisor
x_mult = 4
Lastly, the dividend is subtracted from the x_mult
dividend - x_mult = 1
The modulus operation ,therefore, returns 1:
5 % 2 = 1
Application to apply the modulus to a fraction
Example: 2 % 5
The calculation of the modulus when applied to a fraction is the same as above; however, it is important to note that the integer division will result in a value of zero when the divisor is larger than the dividend:
dividend = 2
divisor = 5
The integer division results in 0 whereas the; therefore, when step 3 above is performed, the value of the dividend is carried through (subtracted from zero):
dividend - 0 = 2 —> 2 % 5 = 2
Application to apply the modulus to a negative
Floor division occurs in which the value of the integer division is rounded down to the lowest integer value:
import math
x = -1.1
math.floor(-1.1) = -2
y = 1.1
math.floor = 1
Therefore, when you do integer division you may get a different outcome than you expect!
Applying the steps above on the following dividend and divisor illustrates the modulus concept:
dividend: -5
divisor: 2
Step 1: Apply integer division
x_int = -5 // 2 = -3
Step 2: Multiply the result of the integer division by the divisor
x_mult = x_int * 2 = -6
Step 3: Subtract the dividend from the multiplied variable, notice the double negative.
dividend - x_mult = -5 -(-6) = 1
Therefore:
-5 % 2 = 1
Be aware that
(3 +2 + 1 - 5) + (4 % 2) - (1/4) + 6
even with the brackets results in 6.75 instead of 7 if calculated in Python 3.4.
And the '/' operator is not that easy to understand, too (python2.7): try...
- 1/4
1 - 1/4
This is a bit off-topic here, but should be considered when evaluating the above expression :)
The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type.
3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 = 7
This is based on operator precedence.
% is modulo. 3 % 2 = 1, 4 % 2 = 0
/ is (an integer in this case) division, so:
3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
1 + 4%2 - 1/4 + 6
1 + 0 - 0 + 6
7
It's a modulo operation
http://en.wikipedia.org/wiki/Modulo_operation
http://docs.python.org/reference/expressions.html
So with order of operations, that works out to
(3+2+1-5) + (4%2) - (1/4) + 6
(1) + (0) - (0) + 6
7
The 1/4=0 because we're doing integer math here.
It is, as in many C-like languages, the remainder or modulo operation. See the documentation for numeric types — int, float, long, complex.
Modulus - Divides left hand operand by right hand operand and returns remainder.
If it helps:
1:0> 2%6
=> 2
2:0> 8%6
=> 2
3:0> 2%6 == 8%6
=> true
... and so on.
I have found that the easiest way to grasp the modulus operator (%) is through long division. It is the remainder and can be useful in determining a number to be even or odd:
4%2 = 0
2
2|4
-4
0
11%3 = 2
3
3|11
-9
2
def absolute(c):
if c>=0:
return c
else:
return c*-1
x=int(input("Enter the value:"))
a=absolute(x)
print(a)