这里的python初学者。
随机生成300个点,其中x和y介于0和1之间。
我需要计算在单位圆内生成的点数,并使用这些点估计pi。我通常希望代码与此类似(我到目前为止):
import math
import random
points = 300
x = [random.random() for jj in range(points)]
y = [random.random() for xx in x]
count = 0
for xx, yy in zip(x,y) :
if xx**2 + yy**2 < 1:
do_not_count_it
else:
count_it
sum = all_points_in_unit_circle
有关如何完成代码的任何建议吗?
答案 0 :(得分:1)
你很亲密
else:
)。 < 1
)sum
和count
相同。sqrt()
,但是从sqrt(1)==1
开始,它将毫无用处。 给出了:
import random
points = 300
x = [random.random() for jj in range(points)]
y = [random.random() for xx in x]
count = 0
for xx, yy in zip(x,y) :
if xx * xx + yy * yy < 1:
count += 1
print (count)
BTW,它适用于pyhton2和python3。
答案 1 :(得分:0)
我对Monte Carlo方法不太熟悉,但快速阅读告诉我你应该只做
for xx, yy in zip(x,y) :
if xx**2 + yy**2 <= 1:
count+=1
然后就像这样近似pi
approxPi = 4.0 * count / points
答案 2 :(得分:0)
你也可以这样做:
from random import random
num_of_points = 300
points = [(random(), random()) for _ in range(num_of_points)]
points_inside = sum(x**2 + y**2 < 1 for x, y in points)
答案 3 :(得分:-1)
这里圆的半径是0.5,圆的面积是 Pi * 0.5 ^ 2 = Pi * 0.25 ;方块为1x1,方形区域为 1x1 = 1 。
#point_in_circle / #point_in_square = area_of_circle / area_of_square ,
所以我们有 circle_count / all_count = Pi * 0.25 / 1
我们得到 Pi = circle_count / all_count * 1 / 0.25
此代码将打印出PI值:
import math
import random
points = 300
x = [random.random() for jj in range(points)]
y = [random.random() for xx in x]
count_circle = 0
for xx, yy in zip(x,y) :
if xx**2 + yy**2 <= 1:
count_circle += 1
pi = count_circle/points/0.25
print (pi)