<jupyter_start><jupyter_text>> This is one of the 100 recipes of the [IPython Cookbook](http://ipython-books.github.io/), the definitive guide to high-performance scientific computing and data science in Python.  5.1. Accelerating pure Python code with Numba and Just-In-Time compilation In this example, we first write a pure Python version of a function that generates a Mandelbrot fractal. Then, we use Numba to compile it dynamically to native code.<jupyter_code>import numpy as np<jupyter_output><empty_output><jupyter_text>We initialize the simulation and generate the gridin the complex plane.<jupyter_code>size = 200
iterations = 100<jupyter_output><empty_output><jupyter_text>Pure Python version The following function generates the fractal.<jupyter_code>def mandelbrot_python(m, size, iterations):
    for i in range(size):
        for j in range(size):
            c = -2 + 3./size*j + 1j*(1.5-3./size*i)
            z = 0
            for n in range(iterations):
                if np.abs(z) <= 10:
                    z = z*z + c
                    m[i, j] = n
                else:
                    break
m = np.zeros((size, size))
mandelbrot_python(m, size, iterations)
import matplotlib.pyplot as plt
%matplotlib inline
plt.imshow(np.log(m), cmap=plt.cm.hot,);
plt.xticks([]); plt.yticks([]);
%%timeit m = np.zeros((size, size))
mandelbrot_python(m, size, iterations)<jupyter_output><empty_output><jupyter_text>Numba version We first import Numba.<jupyter_code>import numba
from numba import jit, complex128<jupyter_output><empty_output><jupyter_text>Now, we just add the `@jit` decorator to the exact same function.<jupyter_code>@jit(locals=dict(c=complex128, z=complex128))
def mandelbrot_numba(m, size, iterations):
    for i in range(size):
        for j in range(size):
            c = -2 + 3./size*j + 1j*(1.5-3./size*i)
            z = 0
            for n in range(iterations):
                if abs(z) <= 10:
                    z = z*z + c
                    m[i, j] = n
                else:
                    break
m = np.zeros((size, size))
mandelbrot_numba(m, size, iterations)
%%timeit m = np.zeros((size, size))
mandelbrot_numba(m, size, iterations)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.11096075778078485, 'fraction_numerical': 0.017140279657194408, 'mean_word_length': 2.974910394265233, 'pattern_counts': {'":': 0, '<': 23, '<?xml version=': 0, '>': 22, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '380301', 'license': 'BSD-2-Clause', 'n_tokens_mistral': 774, 'n_tokens_neox': 730, 'n_words': 211, 'path': 'notebooks/chapter05_hpc/01_numba.ipynb', 'repo_name': 'khanparwaz/PythonProjects', 'size': '2217'}