from numba import jit import random @jit(nopython=True) def monte_carlo_pi(nsamples): acc = 0 for i in range(nsamples): x = random.random() y = random.random() if (x ** 2 + y ** 2) < 1.0: acc += 1 return 4.0 * acc / nsamples
Here is what the above code is Doing:
1. The @jit decorator tells Numba to compile this function.
2. The argument nopython=True tells Numba to generate code that does not access the Python C API.
3. The function contains only NumPy and Python built-in operations so this restriction is not a problem.
4. The function is compiled and the returned object is a regular Python function.
5. The function can be called like any other Python function.