python modulo operation for basic mathematics operation [duplicate] - python

I'm embarrassed to ask such a simple question. My term does not start for two more weeks so I can't ask a professor, and the suspense would kill me.
Why does 2 mod 4 = 2?

Mod just means you take the remainder after performing the division. Since 4 goes into 2 zero times, you end up with a remainder of 2.

Modulo is the remainder, not division.
2 / 4 = 0R2
2 % 4 = 2
The sign % is often used for the modulo operator, in lieu of the word mod.
For x % 4, you get the following table (for 1-10)
x x%4
------
1 1
2 2
3 3
4 0
5 1
6 2
7 3
8 0
9 1
10 2

Modulo (mod, %) is the Remainder operator.
2%2 = 0 (2/2 = 1 remainder 0)
1%2 = 1 (1/2 = 0 remainder 1)
4%2 = 0 (4/2 = 2 remainder 0)
5%2 = 1 (5/2 = 2 remainder 1)

Much easier if u use bananas and a group of people.
Say you have 1 banana and group of 6 people, this you would express: 1 mod 6 / 1 % 6 / 1 modulo 6.
You need 6 bananas for each person in group to be well fed and happy.
So if you then have 1 banana and need to share it with 6 people, but you can only share if you have 1 banana for each group member, that is 6 persons, then you will have 1 banana (remainder, not shared on anyone in group), the same goes for 2 bananas. Then you will have 2 banana as remainder (nothing is shared).
But when you get 6 bananas, then you should be happy, because then there is 1 banana for each member in group of 6 people, and the remainder is 0 or no bananas left when you shared all 6 bananas on 6 people.
Now, for 7 bananas and 6 people in group, you then will have 7 mod 6 = 1, this because you gave 6 people 1 banana each, and 1 banana is the remainder.
For 12 mod 6 or 12 bananas shared on 6 people, each one will have two bananas, and the remainder is then 0.

2 / 4 = 0 with a remainder of 2

I was confused about this, too, only a few minutes ago. Then I did the division long-hand on a piece of paper and it made sense:
4 goes into 2 zero times.
4 times 0 is 0.
You put that zero under the 2 and subtract which leaves 2.
That's as far as the computer is going to take this problem. The computer stops there and returns the 2, which makes sense since that's what "%" (mod) is asking for.
We've been trained to put in the decimal and keep going which is why this can be counterintuitive at first.

Someone contacted me and asked me to explain in more details my answer in the comment of the question. So here is what I replied to that person in case it can help anyone else:
The modulo operation gives you the remainder of the euclidian disivion
(which only works with integer, not real numbers). If you have A such
that A = B * C + D (with D < B), then the quotient of the euclidian division of A
by B is C, and the remainder is D. If you divide 2 by 4, the quotient
is 0 and the remainder is 2.
Suppose you have A objects (that you can't cut). And you want to
distribute the same amount of those objects to B people. As long as
you have more than B objects, you give each of them 1, and repeat.
When you have less than B objects left you stop and keep the remaining
objects. The number of time you have repeated the operation, let's
call that number C, is the quotient. The number of objects you keep at
the end, let's call it D, is the remainder.
If you have 2 objects and 4 people. You already have less than 4
objects. So each person get 0 objects, and you keep 2.
That's why 2 modulo 4 is 2.

The modulo operator evaluates to the remainder of the division of the two integer operands. Here are a few examples:
23 % 10 evaluates to 3 (because 23/10 is 2 with a remainder of 3)
50 % 50 evaluates to 0 (50/50 is 1 with a remainder of 0)
9 % 100 evaluates to 9 (9/100 is 0 with a remainder of 9)

mod means the reaminder when divided by. So 2 divided by 4 is 0 with 2 remaining. Therefore 2 mod 4 is 2.

Modulo is the remainder, expressed as an integer, of a mathematical division expression.
So, lets say you have a pixel on a screen at position 90 where the screen is 100 pixels wide and add 20, it will wrap around to position 10. Why...because 90 + 20 = 110 therefore 110 % 100 = 10.
For me to understand it I consider the modulo is the integer representation of fractional number. Furthermore if you do the expression backwards and process the remainder as a fractional number and then added to the divisor it will give you your original answer.
Examples:
100
(A) --- = 14 mod 2
7
123
(B) --- = 8 mod 3
15
3
(C) --- = 0 mod 3
4
Reversed engineered to:
2 14(7) 2 98 2 100
(A) 14 mod 2 = 14 + --- = ----- + --- = --- + --- = ---
7 7 7 7 7 7
3 8(15) 3 120 3 123
(B) 8 mod 3 = 8 + --- = ----- + --- = --- + --- = ---
15 15 15 15 15 15
3 3
(B) 0 mod 3 = 0 + --- = ---
4 4

When you divide 2 by 4, you get 0 with 2 left over or remaining. Modulo is just the remainder after dividing the number.

I think you are getting confused over how the modulo equation is read.
When we write a division equation such as 2/4 we are dividing 2 by 4.
When a modulo equation is wrote such as 2 % 4 we are dividing 2 by 4 (think 2 over 4) and returning the remainder.

MOD is remainder operator. That is why 2 mod 4 gives 2 as remainder. 4*0=0 and then 2-0=2. To make it more clear try to do same with 6 mod 4 or 8 mod 3.

This is Euclid Algorithm.
e.g
a mod b = k * b + c => a mod b = c, where k is an integer and c is the answer
4 mod 2 = 2 * 2 + 0 => 4 mod 2 = 0
27 mod 5 = 5 * 5 + 2 => 27 mod 5 = 2
so your answer is
2 mod 4 = 0 * 4 + 2 => 2 mod 4 = 2

For:
2 mod 4
We can use this little formula I came up with after thinking a bit, maybe it's already defined somewhere I don't know but works for me, and its really useful.
A mod B = C where C is the answer
K * B - A = |C| where K is how many times B fits in A
2 mod 4 would be:
0 * 4 - 2 = |C|
C = |-2| => 2
Hope it works for you :)

Mod operation works with reminder.
This is called modular arithmetic.
a==b(mod m)
then m|(a-b)
a-b=km
a=b+km
So, 2=2+0*4

To answer a modulo x % y, you ask two questions:
A- How many times y goes in x without remainder ? For 2%4 that's 0.
B- How much do you need to add to get from that back to x ? To get from 0 back to 2 you'll need 2-0, i.e. 2.
These can be summed up in one question like so:
How much will you need to add to the integer-ish result of the division of x by y, to get back at x?
By integer-ish it is meant only whole numbers and not fractions whatsoever are of interest.
A fractional division remainder (e.g. .283849) is not of interest in modulo because modulo only deals with integer numbers.

For a visual way to think about it, picture a clock face that, in your particular example, only goes to 4 instead of 12. If you start at 4 on the clock (which is like starting at zero) and go around it clockwise for 2 "hours", you land on 2, just like going around it clockwise for 6 "hours" would also land you on 2 (6 mod 4 == 2 just like 2 mod 4 == 2).

This could be a good time to mention the modr() function. It returns both the whole and the remainder parts of a division.
print("\n 17 // 3 =",17//3," # Does the same thing as int(17/3)")
print(" 17 % 3 =",17%3," # Modulo division gives the remainder.")
whole, remain = divmod(17,3)
print(" divmod(17,3) returns ->",divmod(17,3),end="")
print(" because 3 goes into 17,",whole,"times with a remainder of",remain,end=".\n\n")

The way I go about it is, 2%4 can be interpreted as what is the highest factor of 4 that is less or equal to 2, and that is 0, therefore 2 (the left operand from 2%4) minus(-) 0 is 2

Related

Table of Squares and Cubes

I am learning Python on my own and I am stuck on a problem from a book I purchased. I can only seem to get the numbers correctly, but I cannot get the title. I was wondering if this has anything to do with the format method to make it look better? This is what I have so far:
number = 0
square = 0
cube = 0
for number in range(0, 6):
square = number * number
cube = number * number * number
print(number, square, cube)
What I am returning:
0 0 0
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
I would like my desired output to be this:
number square cube
0 0 0
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
Here we can specify the width of the digits using format in paranthesis
print('number square cube')
for x in range(0, 6):
print('{0:6d}\t {1:7d}\t {2:3d}'.format(x, x*x, x*x*x))
This would result in
number square cube
0 0 0
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
You need to print the header row. I used tabs \t to space the numbers our properly and f-stings because they are awesome (look them up).
number = 0
square = 0
cube = 0
# print the header
print('number\tsquare\tcube')
for number in range(0, 6):
square = number * number
cube = number * number * number
# print the rows using f-strings
print(f'{number}\t{square}\t{cube}')
Output:
number square cube
0 0 0
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
The only thing this doesn't do is right-align the columns, you'd have to write some custom printing function for that which determines the proper width in spaces of the columns based on each item in that column. To be honest, the output here doesn't make ANY difference and I'd focus on the utility of your code rather than what it looks like when printing to a terminal.
There is a somewhat more terse method you might consider that also uses format, as you guessed. I think this is worth learning because the Format Specification Mini-Language can be useful. Combined with f-stings, you go from eight lines of code to 3.
print('number\tsquare\tcube')
for number in range(0, 6):
print(f'{number:>6}{number**2:>8}{number**3:>6}')
The numbers here (e.g.:>6) aren't special but are just there to get you the output you desired. The > however is, forcing the number to be right-aligned within the space available.

3x3 magic square with unknown magic constant (sum)

I am trying to fill missing fields in a 3x3 matrix (square) in order to form a magic square (row, columns both diagonals sum are the same, filled with any none repeating positive integers ).
an example of such square will be like :
[_ _ _]
[_ _ 18]
[_ 28 _]
Since it doesn't follow the basic rules of the normal magic square where its integers are limited to 1-9(from 1 to n^2). , the magic constant (sum) is not equal to 15
(n(n^2+1)/2) rather it's unknown and has many possible values.
I tried a very naïve way where I generated random numbers in the empty fields with an arbitrary max of 99 then I took the whole square passed it into a function that checks if it's a valid magic square.
It basically keeps going forever till it finds the combination of numbers in the right places.
Needless to say, this solution was dumb, it keeps going for hours before it finds the answer if ever.
I also thought about doing an exhaustive number generation (basically trying every combination of numbers) till I find the right one but this faces the same issue.
So I need help figuring out an algorithm or some way to limit the range of random number generated
3 by 3 magic squares are a vector space with these three basis elements:
1 1 1 0 1 -1 -1 1 0
1 1 1 -1 0 1 1 0 -1
1 1 1 1 -1 0 0 -1 1
You can introduce 3 variables a, b, c that represent the contribution from each of the 3 basis elements, and write equations for them given your partial solution.
For example, given your example grid you'll have:
a + b - c = 18
a - b - c = 28
Which immediately gives 2b = 10 or b=-5. And a-c = 23, or c=a-23.
The space of solutions looks like this:
23 2a-28 a+5
2a-18 a 18
a-5 28 2a-23
You can see each row/column/diagonal adds up to 3a.
Now you just need to find integer solutions for a and c that satisfy your positive and non-repeating constraints.
For example, a=100, b=-5, c=77 gives:
23 172 105
182 100 18
95 28 177
The minimal sum magic square with positive integer elements occurs for a=15, and the sum is 3a=45.
23 2 20
12 15 18
10 28 7
It happens that there are no repeats here. If there were, we'd simply try the next larger value of a and so on.
A possible approach is translating the given numbers to other values. A simple division is not possible, but you can translate with (N-13)/5. Then you have a partial filled in square:
- - - 2 7 6
- - 1 for which there is a solution 9 5 1
- 3 - 4 3 8
When you translate these numbers back with (N*5)+13, you obtain:
23 48 43
58 38 18 which sums up to 114 in all directions (5 * 15) + (3 * 13)
33 28 53

What is the reason for difference between integer division and float to int conversion in python?

I have recently noticed that int() rounds a float towards 0, while integer division rounds a float towards its floor.
for instance:
-7 // 2 == -4
int(-7/2) == -3
I have read the documentation which specifies:
class int(x, base=10)
Return an integer object constructed from a number or string x, or return 0 if no arguments are >given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero.
and:
floor division
Mathematical division that rounds down to nearest integer. The floor division operator is //. For example, the expression 11 // 4 evaluates to 2 in contrast to the 2.75 returned by float true division. Note that (-11) // 4 is -3 because that is -2.75 rounded downward. See PEP 238.
But it seems illogical for me that 2 similar operations (float division to integer) should return different results.
Is there any motivation for the differences between the functions?
Consistency.
You'll need to follow some very basic and seemingly irrelevant explanations to understand it.
In school you have learned division with a remainder. And you have done calculations like this:
8 ÷ 4 = 2 R 0
7 ÷ 4 = 1 R 3
6 ÷ 4 = 1 R 2
5 ÷ 4 = 1 R 1
4 ÷ 4 = 1 R 0
3 ÷ 4 = 0 R 3
2 ÷ 4 = 0 R 2
1 ÷ 4 = 0 R 1
0 ÷ 4 = 0 R 0
^------ This is the result of x // 4
^-- This is the result of x % 4 (modulo)
Later, you have learned divisions for real numbers:
8 ÷ 4 = 2.0
7 ÷ 4 = 1.75
6 ÷ 4 = 1.5
5 ÷ 4 = 1.25
4 ÷ 4 = 1.0
3 ÷ 4 = 0.75
2 ÷ 4 = 0.5
1 ÷ 4 = 0.25
0 ÷ 4 = 0.0
^--- Note that the number in front of the . is int(x/4)
Until this point, you might believe that x // 4 and int(x/4) always give the same result. That's your current understanding of the situation.
However, have a look what happens in the integer division: the number behind R cycles from 3, 2, 1 to 0 and then restarts: 3, 2, 1, 0. The number in front of the R decreses every 4th step.
So, how will it go on?
8 ÷ 4 = 2 R 0
7 ÷ 4 = 1 R 3
6 ÷ 4 = 1 R 2
5 ÷ 4 = 1 R 1
4 ÷ 4 = 1 R 0
3 ÷ 4 = 0 R 3
2 ÷ 4 = 0 R 2
1 ÷ 4 = 0 R 1
0 ÷ 4 = 0 R 0
-1 ÷ 4 = -1 R 3
^------ We have to decrease now, because we already have 0 four times
^-- We have to restart the cycle at 3
At the same time, the real number division gives us:
-1 ÷ 4 = -0.25
^----- There is still a 0 in front of the .
That's why -1 // 4 gives -1 but int(-1/4) gives 0.
Is there any motivation for the differences between the functions?
Well, they serve different purposes: // is part of an integer calculation with remainders and int() gives you the part in front of the . of a real number operation.
You decide what you want to calculate, then you decide which operator to use in Python to get the correct result.
Good question. Keep on learning.
I would say that your observation that those 2 operations should be intuitively similar is expected since on positive numbers they behave identically. But if you look at their origins (one comes from mathematics and the other from computer science) then it makes more sense their different behavior.
You can look behind there concepts:
Floor division aka the floor function applied to the math division
Type conversion/Type casting
==================================================================
I)Floor division aka the floor function applied to the math division
The floor function is a very well established concept in mathematics.
From mathworld.wolfram:
The floor function |_ x_ |, also called the greatest integer function or integer value (Spanier and Oldham 1987), gives the largest integer less than or equal to x. The name and symbol for the floor function were coined by K. E. Iverson (Graham et al. 1994)
So floor division is nothing more than floor function applied to the math division. The behavior is very clear, "mathematically precise".
II)Type conversion/Type casting
From wikipedia:
In computer science, type conversion, type casting, type
coercion and type juggling are different ways of changing an
expression from one data type to another.
In most of the programming languages, the casting form float to integer is applied by rounding rule (so there is a convention) :
Round toward 0 – directed rounding towards zero (also known as
truncation)
Rounding rule according to IEEE 754.
So, in other words, the reason for the difference between integer division and float to int conversion in python is a mathematical one, here are some thoughts from Guido van Rossum (I guess I do not have to introduce him :D) (from the blog The history of Python, article "Why Python's Integer Division Floors")
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).
Based on the answer by #thomas-weller I also found myself a maybe novice explanation for the floor division result from his example of division with a remainder:
7 / 4 = 1 R 3 = 1 + 0,75 = 1.75
-> R3 = 3/4 = 0.75
-1 /4 = -1 R 3 = -1 + 0,75 (R3) = -0.25

Check a variable is a multiple of 10

I need my program to check an in putted variable (e_gtin) and then calculate the GTIN from it (times the 1,3,5 and 7th number by three then add the 7 numbers up and divide by the nearest 10 times table) So far, it times the numbers and adds them up but I don't know where to go from there in terms of making it a multiple of ten
In Addition i eventually used this code
calculator = int(e_gtin[0])*3+int(e_gtin[1])+\
int(e_gtin[2])*3+int(e_gtin[3])+\
int(e_gtin[4])*3+int(e_gtin[5])+\
int(e_gtin[6])*3
rounding = round(calculator+4)
The plus 4 is so the variable will always round up rather than rounding down (The GTIN calculation specifies this)
e_gtin being an inputted 7 digit GTIN code.
Thanks go to --->
https://stackoverflow.com/users/906693/roadrunner66
You are presumably asking about calculating the check-digit on a GTIN8 number. An explanation is given here http://www.gs1.org/how-calculate-check-digit-manually
e = input("Enter a 7 digit number - ")
# note: an integer number can not be accessed like a string or list,
# make it a string first
e=str(e)
sum= int(e[0])*3+int(e[1])+\
int(e[2])*3+int(e[3])+\
int(e[4])*3+int(e[5])+\
int(e[6])*3
checkdigit = 9 - (sum-1) % 10
print sum,checkdigit
To understand the working of a the modulo operator, just play with it, make yourself a table etc.
import numpy as np
sums=np.array([50,51,52,53,54,55,56,57,58,59,60,61])
print sums
print sums % 10
print 10 - sums % 10 # all results right except for 10s which should be zeros
print 10 - (sums-1) % 10 -1
output:
[50 51 52 53 54 55 56 57 58 59 60 61]
[0 1 2 3 4 5 6 7 8 9 0 1]
[10 9 8 7 6 5 4 3 2 1 10 9]
[0 9 8 7 6 5 4 3 2 1 0 9]

If there are slots consisting of n numbers, which will x fit into?

This is a little bit hard to phrase... Basically, my question is as follows. If all the numbers up to z are divided into groups of n, which will x fit into. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|_______| |_______| |___________|
0 1 2
so in this example, n = 5, there are groups of five. z = 15. Let's say x = 9. How can I write a function that will return 1 for x = 9 because its in the group with the index position of 1, and that will return 2 for x = 12? I'm having trouble researching this, because I'm having a hard time explaining it. I get the feeling it's deceptively simple... I'm using python 2.7. Thanks in advance.
P.S. I hope this question follows the guidelines for good questions, I seem to be having trouble with that :P
Just divide x by n. The only hitch is that you need to subtract 1 first, because your sequence starts at 1 rather than 0.
def whichSlot(x, n):
return (x - 1) // n
If n are all the same size, it's simple integer division
(x-1)//5

Categories

Resources