[Python] How to make faster Mandelbrot set plot

Discussão em 'Python' iniciado por Stack, Março 25, 2025.

  1. Stack

    Stack Membro Participativo

    Ive written a function which uses turtle to draw a Mandelbrot set, however its very slow (~10's minutes) for any decent resolution, how could I make my code more efficient?

    import math, turtle

    screen = turtle.Screen()
    screen.setup(width=1000, height=600 ,startx=0, starty=0)
    screen.bgcolor('black')
    screen.tracer(0)
    pen = turtle.Turtle()
    pen.penup()
    pen.speed(10)
    width = 800
    height = 600
    MAX_ITER=80

    def draw_mandelbrot(c):
    z = 0
    n = 0
    while abs(z) <= 2 and n < MAX_ITER:
    z = z * z + c
    n += 1
    return n

    def generate_mandelbrot_set(StartR, StartI, EndR, EndI):
    screen.setworldcoordinates(StartR, StartI, EndR, EndI)
    screen.bgcolor("black")
    for x in range(width):
    for y in range(height):
    c = complex(StartR + (x / width) * (EndR - StartR), StartI + (y / height) * (EndI - StartI))
    m = draw_mandelbrot(c)
    color = (255 - int(m * 255 / MAX_ITER)) / 255
    pen.goto(StartR + (x / width) * (EndR - StartR), StartI + (y / height) * (EndI - StartI))
    if y == 0:
    pen.pendown()
    elif y == height-1 :
    pen.penup()
    pen.color(color, color, color)
    pen.dot()

    generate_mandelbrot_set(-2,-1,1,1)

    screen.update()
    screen.mainloop()


    Im new to coding so any advice would be hugely appreciated!

    Continue reading...

Compartilhe esta Página