如何使用Numba模拟PI的近似值?
我想使用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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
此函数
将在x,y时终止
sqrt(x*x+y*y)&lt; = 1
保留,换句话说,您的转弯数量
循环不是确定性的(1到10之间的任何值)。如果要为的上述的恒定弯曲数,则需要放置
返回
外部该循环的主体,这也适用于pi> pi
围成菌,应该在收集数据后进行,即您的代码应该是This function
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 yourfor
loop is not deterministic (any value between 1 and 10). If you want constant number of turns of saidfor
you need to putreturn
outside body of said loop, this also apply topi
calucation as it should be done after data is collected, that is your code should be