Home > OS >  How to simulate an approximation of pi with Numba?
How to simulate an approximation of pi with Numba?

Time:06-13

I would like to approximate the value of pi using a Monte Carlo method, with different input points (10, 10**1 and so on) and get the code faster with Numba.

Here as follows, there is a simulation with inputs = 10

import numba
from random import *
import math
from math import sqrt

@numba.jit(nopython=True)
def go_fast(pi): 
    inside = 0
    inputs =10
    for i in range(0,inputs):
        x=random()
        y=random()
        if sqrt(x*x y*y)<=1:
            inside =1
            pi=4*inside/inputs 
            return (pi)

pi = math.pi      
go_fast(pi)

I would just like to make sure that the simulation was correctly set since the result get from here seems a bit misleading. Thanks

CodePudding user response:

This function

def go_fast(pi): 
    inside = 0
    inputs =10
    for i in range(0,inputs):
        x=random()
        y=random()
        if sqrt(x*x y*y)<=1:
            inside =1
            pi=4*inside/inputs 
            return (pi)

would terminate as soon as x, y for which sqrt(x*x y*y)<=1 hold will be encountered, in other words number of turns of your for loop is not deterministic (any value between 1 and 10). If you want constant number of turns of said for you need to put return outside body of said loop, this also apply to pi calucation as it should be done after data is collected, that is your code should be

def go_fast(pi): 
    inside = 0
    inputs =10
    for i in range(0,inputs):
        x=random()
        y=random()
        if sqrt(x*x y*y)<=1:
            inside =1
    pi=4*inside/inputs 
    return pi
  • Related