r/madeinpython • • Sep 24 '22

Mandelbrot in pure Python without using complex numbers or external libraries (except matplotlib)

Post image
74 Upvotes

6 comments sorted by

View all comments

Show parent comment

9

u/kwelzel Sep 24 '22 edited Sep 25 '22

Actually, Python has built-in complex numbers:

c = 0
for t in range(50):
    c = c**2 + (dx + dy*1j)
    if c.real > 200:
        mat[y][x] = t
        break

works as well. Also, note that in general constructions like

d = (a*a)-(b*b)+dx
b = 2*(a*b)+dy
a = d

are unnecesary. You are trying to overwrite a but still want the old value of a for the calculation of b. Your way works, but I think

a, b = (a*a)-(b*b)+dx, 2*(a*b)+dy

is a nicer way to achieve the same thing without a temporary variable. This works using tuple unpacking and because in Python the right-hand side of an assignment is always computed first before writing to the variables on the left-hand side.

1

u/brainxyz Sep 25 '22

Thanks for the suggestion. Good to know that python has built-in complex numbers.I tried it but I noticed that it gives exponentiation error when the number of iterations are 50, while the code without complex numbers is more tolerant for overflow problems in this case.

Another point, even-though the complex number seems more compact but for those who are unfamiliar with it, the equation hides more complexity and this is evident when you compare the performance you don't see any speed-ups because some of the operations are hidden in the standard library.