问题二代码: 思路: 跟上述问题类似,这里可以求出圆的面积所占的百分比
from random import random import math def x(): DARTS = 10000 hits = 0.0 for i in range(1, DARTS + 1): x, y = random(), random() dis = x * x + y * y if dis < 1: hits = hits + 1 p = (hits / DARTS) print("求出的值为{}".format(p)) print("理论值为{}".format(math.pi / 4)) if __name__=="__main__": x()问题3代码:思路 利用向类似的方法,并且去重复可以用集合, 从而判断是否有人的生日是否是同一天
from random import randint import math DARTS=10000 hits=0.0 for i in range(1,DARTS+1): a = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] b = set() for m in range(30): a[m]=randint(1,365) for j in range(30): b.add(a[j]) if len(b)<30: hits=hits+1 p=hits/DARTS print("求出的值为{}".format(p)) s=1.0 for i in range(0,30): s*=(365-i)/365 print("理论值是{}".format(1-s))理论值:
Lab1.1 理论值: 0.75
Lab1.2 理论值:pi / 4
Lab1.3 理论值:自己算法吧