How to render Mandelbrot Set faster?

前端 未结 6 1521
臣服心动
臣服心动 2020-12-20 07:34

I\'m currently drawing the Mandelbrot set pixel by pixel with PhotoImage and tkinter. I\'m using basically the algorithm directly with no modifications. Are there methods to

6条回答
  •  误落风尘
    2020-12-20 07:55

    Complex numbers in python can be slow, especially if you call abs(x) every iteration. Representing the complex number with c_r and c_i, for real and imaginary parts, reduces the number of calculations you do every iteration.

    def mandel(c):
        z = 0
        for i in range(ITERATIONS):
            z = z**2 + c
            if abs(z) > 2:
                return i     
        return ITERATIONS
    

    instead of z = 0, replace it with z_r,z_i=0,0 we also have to change c in the parameters. Now we have:

    def mandel(c_r,c_i):
        z_r = 0
        z_i = 0
        for i in range(ITERATIONS):
            z = z**2 + c
            if abs(z) > 2:
                return i     
        return ITERATIONS
    

    Instead of using abs(z) > 2, we can now use z_r * z_r + z_i + z_i > 4 Also, we replace z**2 + c with a new version using our new variables (Know that (a+bi)^2 = a^2 - b^2 + 2abi

    def mandel(c_r,c_i):
        z_r = 0
        z_i = 0
        z_r_squared = 0
        z_i_squared = 0
        for i in range(ITERATIONS):
            z_r_squared = z_r * z_r
            z_i_squared = z_i * z_i
            z_r = z_r_squared - z_i_squared + c_r
            z_i = 2 * z_r * z_i + c_i
    
            if z_r_squared + z_r_squared > 4:
                return i     
        return ITERATIONS
    

    Finally, you have to change where the mandelbrot function is called, so

    i = mandel(complex(real, imag))
    

    becomes

    i = mandel(real, imag)
    

提交回复
热议问题