大家好,我是python的业余爱好者。 我在下面编写了以下代码。
for _ in range(10):
x = random.random()
print("Your x coordinates are",x)
y = random.random()
print("Your y coordinates are",y)
distance = x**2 + y**2
distance2 = math.sqrt(distance)
print("The distance of your pair of points is",distance2)
它将打印10个随机生成的坐标,并使用毕达哥拉斯(Monte carlo模拟)计算每对坐标的距离。 我现在创建了一个名为:
的计数器inside = 0
每当一对坐标的距离在0和1之间时,此计数器需要加1。如果距离大于一个,则计数器将不增加。我已经使用while循环和if语句解决了这个问题,但是我无法掌握它。有人可以帮忙吗?
亲切的问候。
答案 0 :(得分:3)
inside = 0
for _ in range(10):
...
if distance2 <= 1:
inside += 1
应该可以解决!
编辑:我删除了0 <=
检查,因为它是平方根,它将始终大于0
答案 1 :(得分:0)
您可以使用与my answer和your last question类似的方法:
您只需通过sum()对数据中所有为True(== 1)的事物求和:
import random
data = [ (random.random(),random.random()) for _ in range(10)]
# sum up all points from data that are <=1 (and hence `True`)
c = sum(x**2+y**2 <= 1 for x,y in data)
# ^^^^^^^^^^^^^^
# if True then 1 else 0
print(data)
print(c)
print([x**2+y**2 for x,y in data])
输出:
# data
[(0.7871534669693369, 0.6834268129613957), (0.6927388543591473, 0.7409611739266033),
(0.8941640299899396, 0.31599794785329216), (0.8694462709965218, 0.5685622773035531),
(0.5840557539431463, 0.08050013228900998), (0.7337702725369145, 0.5132161897225319),
(0.3972195311920842, 0.663522783123498), (0.6079754465427372, 0.3265026876981836),
(0.7599701022860814, 0.6681620505952428), (0.1663292844826113, 0.20439662041341333)]
# amount of points <= 1
6
# the distances to compare it
[1.0866827892364175, 1.028910581605514, 0.8993840155753416, 1.0791998813223598,
0.3476013950126452, 0.8018096702522117, 0.5980458396844117, 0.47623814867297826,
1.0239950822243569, 0.06944340931292242]
答案 2 :(得分:0)
我尝试了。如果我理解正确,您想计算0到1之间的距离。
distance = []
for _ in range(10):
x = random.random()
y = random.random()
distance1 = math.sqrt(x**2 + y**2)
print(distance1)
#print(x, y, distance1)
distance.append(str(distance1))
counter = 0
count ={}
for i in distance:
if (float(i)< 1):
count[i] = i
if i in count:
counter += 1
打印(计数器)