为条件创建计数器

2024-09-30 08:17:23 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,伙计们,我是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个随机生成的坐标,并使用毕达哥拉斯(montecarlo模拟)计算每对坐标的距离。 我现在创建了一个名为:

inside = 0

每当一对坐标的距离在0和1之间时,此计数器需要递增1。如果距离大于1,计数器将不递增。我曾经尝试过使用while循环和if语句,但是我没有掌握其中的诀窍。有人能帮忙吗?你知道吗

谨致问候。你知道吗


Tags: of代码距离foryour计数器randomare
3条回答

您可以使用类似于my answeryour last question的方法:

您只需通过sum()从数据中总结出所有正确(=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]
inside = 0

for _ in range(10):
  ...
  if distance2 <= 1:
    inside += 1

那应该能解决你的问题!你知道吗

编辑:我删除了0 <=检查,因为它是一个平方根,它总是大于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

打印(计数器)

相关问题 更多 >

    热门问题