我怎样才能让我的Mandelbrot绘图仪更快?

时间:2017-06-09 13:57:15

标签: python numpy plot turtle-graphics mandelbrot

如何让我的Python程序更快?这个程序计算Mandelbrot集并用乌龟绘制它。我认为问题出在for循环中。也许这些步骤花费了太多时间。

import numpy as np
import turtle
turtle.ht()
turtle.pu()
turtle.speed(0)
turtle.delay(0) turtle.colormode(255)

i= int(input("iteration = "))
g = int(input("accuracy  = "))
xmin = float(input("X-min: "))
xmax = float(input("X-max: "))
ymin = float(input("Y-min: "))
ymax = float(input("Y-max: "))
cmode = int(255/i)

input("PRESS TO START")
for x in np.arange(xmin,xmax,1/g):
    for y in np.arange(ymin,ymax,1/g):
        c = x + y * 1j
        z = 0
        t = 1
        for e in range(i):
            z = z * z + c
            if abs(z) > 3:
                turtle.setx(g*c.real)
                turtle.sety(g*c.imag)
                turtle.dot(2,e*cmode,e*cmode,e*cmode)
                t = 0

        if t == 1:
            turtle.setx(g*c.real)
            turtle.sety(g*c.imag)
            turtle.dot(2,"black")

input("Calculated!")
turtle.mainloop()

Here is an example

1 个答案:

答案 0 :(得分:1)

以下返工应该比原来快一百倍:

import numpy as np
import turtle

i = int(input("iteration = "))
g = int(input("accuracy  = "))
xmin = float(input("X-min: "))
xmax = float(input("X-max: "))
ymin = float(input("Y-min: "))
ymax = float(input("Y-max: "))

cmode = int(255 / i)

input("PRESS TO START")

turtle.hideturtle()
turtle.penup()
turtle.speed('fastest')
turtle.colormode(255)
turtle.setundobuffer(None)  # turn off saving undo information

turtle.tracer(0, 0)

for x in np.arange(xmin, xmax, 1 / g):
    for y in np.arange(ymin, ymax, 1 / g):
        c = x + y * 1j
        z = 0
        t = True

        for e in range(i):
            z = z * z + c

            if abs(z) > 3.0:
                turtle.setposition(g * c.real, g * c.imag)
                rgb = e * cmode
                turtle.dot(2, rgb, rgb, rgb)
                t = False
                break

        if t:
            turtle.setposition(g * c.real, g * c.imag)
            turtle.dot(2, "black")

    turtle.update()

print("Calculated!")

turtle.mainloop()

重大变化是使用tracer()update()的组合,以避免在视觉上为用户绘制每个点,并在每个垂直列完成时绘图。