Created
July 1, 2023 10:10
-
-
Save Ednaordinary/9049b56a11433b9b630dd8320afb81b8 to your computer and use it in GitHub Desktop.
Graph the collatz conjecture using Turtle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import turtle as Turtle | |
def sequence(n): | |
steps = 0 | |
while n != 1: | |
if n % 2 == 0: | |
n = n / 2 | |
steps += 1 | |
else: | |
n = n*3 + 1 | |
steps += 1 | |
return steps | |
Turtle.setup() | |
Turtle.screensize(2000, 2000, "white") | |
turtle = Turtle.Turtle() | |
turtle.speed(0) | |
max = 0 | |
for i in range(10000): | |
steps = sequence(i + 1) | |
if steps > max: max = steps | |
turtle.pd() | |
turtle.color("blue") | |
turtle.fd(1) | |
turtle.color("black") | |
turtle.pu() | |
if i % 2: | |
canvaswidth = 2000+(i*2) | |
canvasheight = 2000 + max*2 | |
Turtle.screensize(canvaswidth, canvasheight, "white") | |
ts = Turtle.getscreen().getcanvas() | |
screen = Turtle.getscreen() | |
winwidth = screen.window_width() | |
ts.xview_moveto((((canvaswidth-winwidth)/2)/canvaswidth)+(i/canvaswidth)) | |
turtle.lt(90) | |
turtle.fd(steps) | |
turtle.rt(90) | |
turtle.pd() | |
turtle.fd(1) | |
turtle.pu() | |
turtle.rt(180) | |
turtle.fd(1) | |
turtle.lt(90) | |
turtle.fd(steps) | |
turtle.lt(90) | |
Turtle.mainloop() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment