swimminginsky 发表于 2020-3-10 22:09:54

蒙特卡洛法求pi

import math
import random
import time

countIn = 0
count = 0
i = 0
rounds = 20000
startTime = time.perf_counter()
while i <= rounds:
    x = random.randint(0, 10000)
    #print(x)
    y = random.randint(0, 10000)
    #print(y)
    count += 1
    if math.sqrt(x * x + y * y) <= 10000:
      countIn += 1
      #print('pi= ', float(countIn/count) * 4)
    endTime = time.perf_counter()
    i += 1


print('pi= ', float(countIn/count) * 4, 'the escaped time is %f seconds'%(endTime - startTime))

请大家多多指教

wp231957 发表于 2020-3-10 22:15:31

要是没看到最后一行字,我还以为是秀代码的
页: [1]
查看完整版本: 蒙特卡洛法求pi