-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcollatz.py
More file actions
33 lines (28 loc) · 695 Bytes
/
collatz.py
File metadata and controls
33 lines (28 loc) · 695 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# Import(s)
import matplotlib.pyplot as plt
# Var init and input collection
n = int(input("Enter the initial value (n ∈ ℤ⁺): "))
count = 0
x = [0]
y = []
# Start sequence with n
y.append(n)
# Collatz function
def collatz(z):
# Unification of 3x+1 for odd and x/2 for even
return 0.25*(2 + 7*z + (-1)*(2 + 5*z)*((-1) ** z))
# Repeat until the 4,2,1 loop
while y[-1] != 1.0:
count += 1
x.append(count)
y.append(collatz(y[-1]))
print(y[-1], end=" ")
# Zip coords
for i in list(zip(x, y)):
plt.text(i[0], i[1], f"({i[0]} , {i[1]})")
# Output to graph
plt.xlabel("Iterations")
plt.ylabel("Number (n)")
plt.title(f"Collatz Conjecture for n = {n}")
plt.plot(x, y, "bo-")
plt.show()