Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to simulate an approximation of pi with Numba?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading