用python运行测试

2024-07-05 15:36:33 发布

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

我是一个初学者,当谈到使用Python,并希望做模拟,我估计pi使用试验。我首先对x和y值(介于0和1之间)使用重要的随机数,然后检查这些数字是否在圆内。如果它们是,那么我用公式估算π: (4*(圆内点数/试验次数))。 我的代码附在下面。我用的种子应该是3.02左右,但是我用的是4.00。有人能指出我错在哪里吗?你知道吗

import random 

random.seed(1000)

x_value = random.random()

y_value = random.random()

print(x_value)
print(y_value)

pointsInCircle= 0 
numberOfTrials = 1000

for trials in range(trials):
    if 1 > ((x_value ** 2) + (y_value ** 2)):
        pointsInCircle = pointsInCircle + 1
    else:
        print("No estimation possbile")

pi = 4 * (pointsInCircle/numberOfTrials)

print(pi)

Tags: 代码importvaluepi数字random次数种子
2条回答

下面两行应该进入for循环。在每个线索,它需要有2个随机数,这是不同于以往。你知道吗

x_value = random.random()
y_value = random.random()

因此,代码应该如下所示。你知道吗

import random 

random.seed(1000)

# print(x_value)
# print(y_value)

pointsInCircle= 0 
numberOfTrials = 1000

for trials in range(numberOfTrials):
    x_value = random.random()
    y_value = random.random()
    if 1 > ((x_value ** 2) + (y_value ** 2)):
        pointsInCircle = pointsInCircle + 1
    else:
        print("No estimation possbile")

pi = 4 * (pointsInCircle/numberOfTrials)

print(pi)

从而得到答案3.02。你知道吗

我不确定在没有更多信息的情况下是否可以提供完整的解决方案,但它似乎是pointsInCircle/numberOfTrials == 1,因此pointsInCircle == numberOfTrials。你知道吗

也许可以使用一些打印调试来找到这两个变量的值,看看这是否是问题所在。如果你得到更多的信息,我很乐意进一步帮助你!你知道吗

相关问题 更多 >