0

Read somewhere in my adventure in optimizing my mandelbrot program that if you are for example squaring something. Using the mandelbrot equation as the example that z * z is faster than z**2. Is this true, and if it is why is this so? Is it due to the fact that z**2 still computes trivial cases such as 0?

Dunes
  • 37,291
  • 7
  • 81
  • 97

1 Answers1

2

I am one of the people who have suggested the optimization and yes, it is true. In the example below, squaring with * is over 3 times as fast as with **2.

from timeit import repeat
print(repeat('z*z', 'z=.54321 + .56789j'))
print(repeat('z**2', 'z=.54321 + .56789j'))
# prints
[0.07780417092306088, 0.05484807785182001, 0.05577646621573226]
[0.2081317598277747, 0.19060335713839965, 0.1913974058615736]

Since both operations give the same answer

>>> z*z
(-0.02742194800000003+0.6169670537999999j)
>>> z**2
(-0.02742194800000003+0.6169670537999999j)

the second must eventually do the first (plus whatever else it does.

Terry Jan Reedy
  • 18,414
  • 3
  • 40
  • 52