如何使用Numba模拟PI的近似值?

发布于 2025-02-07 00:20:45 字数 516 浏览 2 评论 0原文

我想使用Monte Carlo方法近似Pi的值,具有不同的输入点(10,10 ** 1,依此类推),并使用NUMBA更快地获取代码。

如下所示,有一个带有输入= 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 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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

自控 2025-02-14 00:20:45

此函数

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)

将在x,y时终止sqrt(x*x+y*y)&lt; = 1保留,换句话说,您的转弯数量循环不是确定性的(1到10之间的任何值)。如果要为的上述的恒定弯曲数,则需要放置返回 外部该循环的主体,这也适用于pi> pi围成菌,应该在收集数据后进行,即您的代码应该是

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文