modulo operation with negative numbers in python [duplicate] - python

This question already has answers here:
How does the modulo (%) operator work on negative numbers in Python?
(12 answers)
Closed last month.
I found this definition for modulo
mod(a, n) = a - n * floor(a / n)
Doing an integer division and then multiplying it again means finding the biggest number smaller than a that is dividable by n without a remainder. Subtracting this from a yields the remainder of the division and by that the modulo."
source:https://torstencurdt.com/tech/posts/modulo-of-negative-numbers/
It seemed to help me understand intuitively, and it worked for cases where both a and n where positive and also cases where a was negative while b was positive. For example:
-10 mod 3
-12 is the largest number smaller than -10 divisible by 3. So the remainder is -10-(-12)=2 which is correct.
But when I tried doing 10 mod -3 my answer was incorrect. Because while 9 is the largest number smaller than 10 divisible by -3 it will give the wrong answer as it would evaluate to 10-9=1.
Instead it is supposed to be 10 -((-4)*(-3))=10-12=-2.
But 12 isn't the biggest number smaller than a.
I understand how to solve for the answer using the formula a= (a//n)(n)+(a%n) in python. But is there an intuitive definition to help me understand?

I found an anser here https://en.wikipedia.org/wiki/Remainder
it seems there are two types of remainders and a programming languages picks which one to use

The Python 3 documentation gives the identity x == (x//y)*y + (x%y), from which it can be deduced that x%y == x - (x//y)*y. // denotes “floor division”; x//y is the greatest integer not greater than x/y.
For x=10 and y==−3, x/y is −3⅓. floor(−3⅓) is −4. Therefore x//y is −4. Then x - (x//y)*y is 10 − (−4)*−3 = 10−12 = −2.
Here is a graph of x%3:
Here is a graph of x%-3:

Related

Difference between modulus (%) and floor division(//) in NumPy?

Recently, I read a book on Numpy which mentions different types of ufuncs, where I was encountered with two different ufuncs, namely 'modulus', denoted by % symbol and 'floor division' //. Can someone explain the difference between them and why two operators are provided to do the the same thing (display reminder of division, according to me)? Please correct, if I am wrong.
Both are valid mathematical functions with different results.
modulus
The modulus-function computes the remainder of a division, which is the "leftover" of an integral division.
floor
The floor-function provides the lower-bound of an integral division. The upper-bound is computed by the ceil function. (Basically speaking, the floor-function cuts off all decimals).
a=5
b=2
print(a%b) # Prints 1 as leftover
print(a//b) # Prints 2, since 5/2=2.5 and the decimal is cut off
print(a - (a//b)*b) # Prints 1, this is the modulo, calculated by the floor function
Assume a= 10, b = 6
a%b will give you the remainder, that is 4
a//b will give you the quotient, that is 1
The relationship between floor division and modulus may be helpful for understanding this:
denominator = 6 # replace with any integer
numerator = 10 # replace with any integer
floor_division_result = numerator//denominator
modulo_result = numerator % denominator
# this assertion will always be true:
assert denominator * floor_division_result + modulo_result == numerator
One way to think of the difference between modulus and floor division is to use an analogy of a clock face
Imagine a hand on this clock. It moves around and points at a number. Let's say a cycle starts (and ends) when the hand points at 12. In this context
modulus, %, is where the hand is pointing right now
floor division is the number of times the hand has completed a cycle
Example 1
In the first cycle when the hand points at 4 the modulus is 4 but the floor division is 0.
4 % 12 # returns 4
4 // 12 # returns 0
Example 2
In the second cycle when the hand points at 4 the modulus is still 4 but the floor division is now 1
16 % 12 # returns 4
16 // 12 # returns 1

My answer is changing with the same code [duplicate]

This question already has answers here:
Why does integer division yield a float instead of another integer?
(4 answers)
Closed 5 months ago.
I am a complete python beginner and I am trying to solve this problem :
A number is called triangular if it is the sum of the first n positive
integers for some n For example, 10 is triangular because 10 = 1+2+3+4
and 21 is triangular because 21 = 1+2+3+4+5+6. Write a Python program
to find the smallest 6-digit triangular number. Enter it as your
answer below.
I have written this program:
n = 0
trinum = 0
while len(str(trinum)) < 6:
trinum = n*(n+1)/2
n += 1
print(trinum)
And it only works in the python I have installed on my computer if I say while len(str(trinum)) < 8: but it is supposed to be while len(str(trinum)) < 6:. So I went to http://www.skulpt.org/ and ran my code there and it gave me the right answer with while len(str(trinum)) < 6: like it's supposed to. But it doesn't work with 6 with the python i have installed on my computer. Does anyone have any idea what's going on?
Short Answer
In Python 3, division is always floating point division. So on the first pass you get something like str(trinum) == '0.5'. Which isn't what you want.
You're looking for integer division. The operator for that is //.
Long Answer
The division operator changed in Python 2.x to 3.x. Previously, the type of the result was dependent on the arguments. So 1/2 does integer division, but 1./2 does floating point division.
To clean this up, a new operator was introduced: //. This operator will always do integer division.
So in Python 3.x, this expression (4 * 5)/2 is equal to 10.0. Note that this number is less than 100, but it has 4 characters in it.
If instead, we did (4*5)//2, we would get the integer 10 back. Which would allow your condition to hold true.
In Python 2, the / operator performs integer division when possible: "x divided by y is a remainder b," throwing away the "b" (use the % operator to find "b"). In Python 3, the / operator always performs float division: "x divided by y is a.fgh." Get integer division in Python 3 with the // operator.
You have two problems here, that combine to give you the wrong answer.
The first problem is that you're using /, which means integer division in Python 2 (and the almost-Python language that Skulpt implements), but float division in Python 3. So, when you run it on your local machine with Python 3, you're going to get floating point numbers.
The second problem is that you're not checking for "under 6 digits" you're checking for "under 6 characters long". For positive integers, those are the same thing, but for floats, say, 1035.5 is only 4 digits, but it's 6 characters. So you exit early.
If you solve either problem, it will work, at least most of the time. But you really should solve both.
So:
n = 0
trinum = 0
while trinum < 10**6: # note comparing numbers, not string length
trinum = n*(n+1)//2 # note // instead of /
n += 1
print(trinum)
The first problem is fixed by using //, which always means integer division, instead of /, which means different things in different Python versions.
The second problem is fixed by comparing the number as a number to 10**6 (that is, 10 to the 6th power, which means 1 with 6 zeros, or 1000000) instead of comparing its length as a string to 6.
Taking Malik Brahimi's answer further:
from itertools import *
print(next(dropwhile(lambda n: n <= 99999, accumulate(count(1))))
count(1) is all the numbers from 1 to infinity.
accumulate(count(1)) is all the running totals of those numbers.
dropwhile(…) is skipping the initial running totals until we reach 100000, then all the rest of them.
next(…) is the next one after the ones we skipped.
Of course you could argue that a 1-liner that takes 4 lines to describe to a novice isn't as good as a 4-liner that doesn't need any explanation. :)
(Also, the dropwhile is a bit ugly. Most uses of it in Python are. In a language like Haskell, where you can write that predicate with operator sectioning instead of a lambda, like (<= 99999), it's a different story.)
The division method in Py2.x and 3.x is different - so that is probably why you had issues.
Just another suggestion - which doesn't deal with divisions and lengths - so less buggy in general. Plus addition is addition anywhere.
trinum = 0
idx =0
while trinum < 99999: #largest 5 digit number
idx += 1
trinum += idx
print trinum
import itertools # to get the count function
n, c = 0, itertools.count(1) # start at zero
while n <= 99999:
n = n + next(c)

What is the significance of % in Python [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm brand new to programming languages and brand new to Python.
I'm still having trouble understanding the significance of %, even though I've read 3 short tutorials that explain it.
Can someone break down what % is doing exactly in this code?
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print n, "=", x, "*", n/x
For numbers it returns the remainder of division (as squiguy pointed out).
10 / 3 is 3 with a remainder of 1.
So 10 % 3 == 1.
It's most common use is to check for divisibility. For example, in that loop it checks if n is divisible by x. For example it can be use to do something every nth time.
for i in range(1, 10):
if i % 3 == 0:
print "I love cats and dogs"
else:
print "I love cats"
Outputs,
I love cats
I love cats
I love cats and dogs
I love cats
I love cats
I love cats and dogs
I love cats
I love cats
I love cats and dogs
The % operator in this case is the Modulo operator
As explained in the spec:
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
In this case, you are finding the remainder in the division n / x
Your code sample iterates from n=2 to n=9. For each n, the inner loop checks for all divisors of n that are greater than 1. For each divisor, it prints out a line showing a factorization of n.
For numbers, it's the modulus operator. For strings, it's the "string interpolation" (or "string formatting") operator.
The specific idiom if n % x == 0: in the code corresponds to a divisibility test. In other words, it will result in True if n is divisible by x (i.e. the remainder of the division n / x is 0). Or, if you want, n is a multiple of x (there is some integer y such that x * y == n).
To explain it better, let's analyze the inner iteration when n (in the outer one) is 6. It would be equivalent to:
for x in range(2, 6):
if 6 % x == 0:
print n, "=", x, "*", n/x
With an execution trace:
x 6 % x 6 % x == 0 6 / x Output
-- ----- ---------- ---------- ------
2 0 True 3 6 = 2 * 3
3 0 True 2 6 = 3 * 2
4 2 False Irrelevant <none>
5 1 False Irrelevant <none>
You can go on and try with other values of n. Or all 9 of them. You will see that, like 6, 8 is an interesting case too. Even slightly more so.
% is the modulus operator: it will return the remainder of what is basically an integer division operation. 5 % 2 = 1, 5 % 5 = 0, etc. In regular integer math, all results are rounded down, so 5 / 2 would return 2, even though two fits into five 2.5 times. Of course 0 is a special case and has undefined behavior in most languages.
In arithmetic, if you are using the set of real numbers (or the rational numbers), and you divide, say, 1/2, you can get 0.5 as the answer. Now, if you constrain yourself to only using the integers, 1/2 would return 0, because, in the integers, 1 is not divisible by 2. One way of doing integer division, then, would be to perform long division, store the integer portion of the result as the result of the integer division, and as to not lose any data, store also the remainder, which is what the % operator returns.
In Python, when you do standard division /, you are actually doing floating point division (so fractions can be represented), and hence 1/2 = 0.5. Now, if you used integer division //, then 1//2 = 0. To obtain this value, python simply performs standard division, and takes the floor of the result. If you were to manually write out the division algorithm on paper, you'd notice that this division has a remainder of 1. The modulus % operator simply returns this remainder.
So, 1/2 = 0.5, 1//2 = 0, and 1%2 = 1.
In other words, % returns the same remainder that you would obtain when doing long division.
_0_ <-- result of (1//2)
2| 1
-0
---
1 <- remainder, result of (1 % 2)

Speeding up my Fermat Factorization function (Python)

My task is to factor very large composite numbers using Fermat's factorization method. The numbers are 1024 bits large, which is around 309 decimal digits.
I have come up with the Python code below, which uses the gmpy2 module for accuracy. It is simply a Python implementation of the pseudo-code shown on the Wikipedia page. I read the "Sieve Improvement" section on that page, but wasn't sure how to implement it.
def fermat_factor(n):
assert n % 2 != 0 # Odd integers only
a = gmpy2.ceil(gmpy2.sqrt(n))
b2 = gmpy2.square(a) - n
while not is_square(b2):
a += 1
b2 = gmpy2.square(a) - n
factor1 = a + gmpy2.sqrt(b2)
factor2 = a - gmpy2.sqrt(b2)
return int(factor1), int(factor2)
def is_square(n):
root = gmpy2.sqrt(n)
return root % 1 == 0 # '4.0' will pass, '4.1212' won't
This code runs fairly fast for small numbers, but takes much too long for numbers as large as those given in the problem. How can I improve the speed of this code? I'm not looking for people to write my code for me, but would appreciate some suggestions. Thank you for any responses.
You need to avoid doing so many square and sqrt operations, especially on large numbers.
The easy way to avoid them is to note that a^2 - N = b^2 must be true for all moduli to be a solution. For example,
a^2 mod 9 - N mod 9 = b^2 mod 9
Let's say your N is 55, so N mod 9 = 1.
Now consider the set of (a mod 9), and square it, modulo 9.
The resulting a^2 mod 9 is the set: {0, 1, 4, 7}. The same must be true for the b^2 mod 9.
If a^2 mod 9 = 0, then 0 - 1 = 8 (all mod 9) is not a solution, since 8 is not a square of a number modulo 9. This eliminates (a mod 9) = {0, 3 and 6}.
If a^2 mod 9 = 1, the 1 - 1 = 0 (all mod 9), so (a mod 9) = {1, 8} are possible solutions.
If a^2 mod 9 = 4, then 4 - 1 = 3 (all mod 9) is not a possible solution.
Ditto for a^2 mod 9 = 7.
So, that one modulus eliminated 7 out of 9 possible values of 'a mod 9'.
And you can have many moduli, each one eliminating at least half of the possibilities.
With a set of, say, 10 moduli, you only have to check about 1 in 1,000 a's for being perfect squares, or having integer square roots. (I use about 10,000 moduli for my work).
Note: Moduli which are powers of a prime are often more useful than a prime.
Also, a modulus of 16 is a useful special case, because 'a' must be odd when N mod 4 is 1,
and 'a' must be even when N mod 4 is 3. "Proof is left as an exercise for the student."
Consider rewriting this script to use only integers instead of arbitrary precision floats.
gmpy has support for integer square root (returns the floor of the square root, calculated efficiently). This can be used for the is_square() function by testing if the square of the square root equals the original.
I'm not sure about gmpy2, but in gmpy.sqrt() requires an integer argument, and returns an integer output. If you are using floats, then that is probably your problem (since floats are very slow as compared to integers, especially when using extended precision). If you are in fact using integers, then is_square() must be doing a tedious conversion from integer to float every time it is called (and gmpy2.sqrt() != gmpy.sqrt()).
For those of you who keep saying that this is a difficult problem, keep in mind that using this method was a hint: The fermat factorization algorithm is based on a weakness present when the composite number to be factored has two prime factors which are close to each other. If this was given as a hint, it is likely that the entity posing the problem knows this to be the case.
Edit: Apparently, gmpy2.isqrt() is the same as gmpy.sqrt() (the integer version of sqrt), and gmpy2.sqrt() is the floating-point version.

What is the result of % in Python?

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)

Categories

Resources