Python:计算单位圆中的(x,y)点,并估算pi

时间:2016-03-10 04:54:14

标签: python random python-3.5 pi

这里的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

有关如何完成代码的任何建议吗?

4 个答案:

答案 0 :(得分:1)

你很亲密

  1. 当点在里面时你只需要一个条件(不需要else:)。
  2. 你颠倒了条件(你算< 1
  3. 变量sumcount相同。
  4. 这不是一个错误,但在可能的情况下使用乘法而不是取幂。
  5. 图书馆数学未使用。您可以使用sqrt(),但是从sqrt(1)==1开始,它将毫无用处。
  6. 给出了:

    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)