zoukankan      html  css  js  c++  java
  • 用python做蒙特卡洛仿真算法

    用python做蒙特卡洛仿真算法

    1. 在(0,1)区间里随机取两个数,求它们的差值小于0.5的概率。请编写python 程序,利用蒙特卡罗仿真方法来求解该问题。
    2. 在(0,1)区间里随机取两个数,求它们的平方和小于1的概率。请编写python 程序,利用蒙特卡罗仿真方法来求解该问题。
    3. 假设一个班上有30名同学,都是1997年出生,问其中至少有两名同学生日相同的概率是多少?(假设没有平年和闰年的区别,一年只有365天)请编写python
      程序,利用蒙特卡罗仿真方法来求解该问题。
      问题1代码:
      思路:
      在0到1之间打一万个点
      找出他们之间差值小于0.5的点数
      求出他们的比值即为概率
    DARTS=10000
    hits=0.0
    for i in range(1,DARTS+1):
        x,y=random(),random()
        dis=abs(x-y)
        if dis<0.5:
            hits=hits+1
    p=hits/DARTS
    print("求出的值为{}".format(p))
    print("理论值{}".format(0.75))

    问题二代码:
    思路:
    跟上述问题类似,这里可以求出圆的面积所占的百分比

    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 理论值:自己算法吧

  • 相关阅读:
    【ZBar】ios错误ignoring file xxx missing required architecture x86_64 in file
    微信内置浏览器UserAgent的判断
    运维技能大全 | Devops Tools 周期表
    Mysql 常用命令集
    Iphone H5上传照片被旋转
    陈小春 相依为命
    Hiveserver2 OOM问题解法
    hiveserver 占用内存过大的问题
    linux查看CPU和内存使用情况
    linux Shell函数
  • 原文地址:https://www.cnblogs.com/Xiong-Jun/p/13515052.html
Copyright © 2011-2022 走看看