Skip to content

Instantly share code, notes, and snippets.

@thr0wn
Last active November 6, 2024 23:22
Show Gist options
  • Save thr0wn/f80eb02b3e25742aece046f075bb0370 to your computer and use it in GitHub Desktop.
Save thr0wn/f80eb02b3e25742aece046f075bb0370 to your computer and use it in GitHub Desktop.
Mandelbrot set generated using python turtle
import turtle
import math
def mandelbrot(z , c , n=20):
if abs(z) > 10 ** 12:
return float("nan")
elif n > 0:
return mandelbrot(z ** 2 + c, c, n - 1)
else:
return z ** 2 + c
# screen size (in pixels)
screenx, screeny = 800, 600
# complex plane limits
complexPlaneX, complexPlaneY = (-2.0, 2.0), (-1.0, 2.0)
# discretization step
step = 2
# turtle config
turtle.tracer(0, 0)
turtle.setup(screenx, screeny)
turtle.bgcolor("#010f7c")
screen = turtle.Screen()
screen.title("Mandelbrot Fractal (discretization step = %d)" % (int(step)))
mTurtle = turtle.Turtle()
mTurtle.penup()
mTurtle.shape("turtle")
# px * pixelToX = x in complex plane coordinates
pixelToX, pixelToY = (complexPlaneX[1] - complexPlaneX[0])/screenx, (complexPlaneY[1] - complexPlaneY[0])/screeny
# plot
for px in range(-screenx/2, screenx/2, int(step)):
for py in range(-screeny/2, screeny/2, int(step)):
x, y = px * pixelToX, py * pixelToY
m = mandelbrot(0, x + 1j * y)
if not math.isnan(m.real):
color = [abs(math.sin(m.imag)) for i in range(3)]
mTurtle.color(color)
mTurtle.dot(2.4, color)
mTurtle.goto(px, py)
turtle.update()
turtle.mainloop()
@yves-chevallier
Copy link

Traceback (most recent call last):
  File "m.py", line 35, in <module>
    for px in range(-screenx/2, screenx/2, int(step)):
TypeError: 'float' object cannot be interpreted as an integer

I guess you should write this instead:

for px in range(-int(screenx/2), int(screenx/2), int(step)):
    for py in range(-int(screeny/2), int(screeny/2), int(step)):

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment