Python For Quantum Mechanics#

Week 1: Binary Operations#

from IPython.display import YouTubeVideo
YouTubeVideo('dMw8E-8cQpc',width=700, height=400)

Overview of Binary#

Why does 9 come berfore 10? It might seem like a silly question but the answer is that that is how humans have decided to write numbers. That is that after ten numbers (0, 1, 2, 3, 4, 5, 6, 7, 8, and 9) we increase the ten’s digit by one. What if instead we chose to do so after just two numbers; that is we start with 0 and then go to 1 but then take 10, and then 11. After that we will have 100 and then 101 and so on. This is known as binary and it is how computers ultimately work with data.

Number in base 10 (decimal)

Number in base 2 (binary)

0

0

1

1

2

10

3

11

4

100

5

101

6

110

7

111

8

1000

9

1001

10

1010

11

1011

12

1100

13

1101

14

1110

15

1111

Base 10 (or decimal) is what we are most used to and that can be thought of in the following way $\(\begin{equation} \begin{split} 1503 &= 1\times 1000 + 5\times 100 + 0\times 10 + 3\times 1 \\ &= 1\times 10^3 + 5\times 10^2 + 0\times 10^1 + 3\times 10^0 \\ \end{split} \end{equation}\)\( so we can read off the digits 1503. Binary numbers can be thought of in a similar way \)\( 1010_{\text(binary)} = 1\times 2^3 + 0\times 2^2 + 1\times 2^1 + 0\times 2^0 = 10_\text{(decimal)}\)$ An alternate method is diagramed below where multiple divisions are performed and the remainders are recorded. two dice

We can cast numbers into binary using the bin() function.

print(bin(146))
0b10010010

Here the 0b tells us we are in binary.

Bitwise Operators#

There is multiple bitwise operators we can use in Python, namely the AND &, OR |, NOT ~, and XOR ^.

a = 10 # 1010
b = 5 #  0101

print("a & b = ", a & b) #Returns 1 if both bits are 1, otherwise returns 0


print("a | b = ", a | b) #Returns 1 if either bits are 1, otherwise returns 0


print("~ b = ", ~b) #Returns the compliment of the number: -(0101 + 0001) = - 6

print("a ^ b = ", a ^ b) #Returns 1 if one bit is 1 and the other is 0, otherwise returns 0
a & b =  0
a | b =  15
~ b =  -6
a ^ b =  15

Shift Operators#

There is also the right >> and left << shift operators. The shift operators have the effect of multiplying or dividing the number by 2.

a = 10 # 1010

print("a >> 1 = ",a >> 1) # 1010 >> 1 = 0101 = 5
print("a >> 2 = ",a >> 2) # 1010 >> 2 = 0010 = 2

print("a << 1 = ",a << 1) # 1010 << 1 = 10100 = 20 
print("a << 2 = ",a << 2) # 1010 << 2 = 101000 = 40 
a >> 1 =  5
a >> 2 =  2
a << 1 =  20
a << 2 =  40