""" cube_bug.py: the same math, two ways. NumPy's ** takes a slow road when the numbers being cubed are negative. """ import time import numpy as np def best_of(fn, reps=7): fn(); ts = [] for _ in range(reps): t = time.perf_counter(); fn(); ts.append(time.perf_counter() - t) return min(ts) rng = np.random.default_rng(0) pos = rng.random(786_432).astype(np.float32) # 3,072 x 256, like one floor for name, h in [("all positive", pos), ("all negative", -pos), ("mixed (real)", pos - 0.5)]: a = best_of(lambda: h ** 3) b = best_of(lambda: h * h * h) print(f"{name:13s} h**3: {a*1e3:6.2f} ms h*h*h: {b*1e3:5.2f} ms ({a/b:4.0f}x)") print("numpy", np.__version__)