Skip to content

蒙特卡洛的入门例子[含python源码] #9

@timest

Description

@timest

阮老师的博客里有一篇蒙特卡洛的入门文章 ,这里附上其中3个python源码。


例子

计算π

image

import random
import math


def is_circle(x, y):
    r = math.sqrt(x ** 2 + y ** 2)
    if r <= 1.0:
        return True
    return False


count_circle = 0
count_square = 0
for i in range(100000):
    x = random.uniform(-1, 1)
    y = random.uniform(-1, 1)
    if is_circle(x, y):
        count_circle += 1
    count_square += 1

pi = (count_circle / count_square) * 4
print(pi)

阴影面积

import random

def is_in_shadow(x, y):
    return True if y <= x**2 else False

count_square = 0
count_shadow = 0
for i in range(1000000):
    x = random.uniform(0, 1)
    y = random.uniform(0, 1)
    if is_in_shadow(x, y):
        count_shadow += 1
    count_square += 1

shadow = count_shadow / count_square
print(shadow)

计算厚度

image

import random

def is_defective(thickness):
    return True if thickness > 27 else False

total = 100000
defective = 0
for i in range(total):
    top_housing = random.uniform(1.909, 2.091)
    clearance = 0.5
    zebra = random.uniform(4.468, 4.682)
    hirose = random.uniform(2.909, 3.091)
    pcb = random.uniform(0.898, 1.102)
    lower_components = random.uniform(12.9, 13.1)
    botton = 0.5
    bottom_housing = random.uniform(1.909, 2.091)

    overall = top_housing + clearance + zebra + hirose + pcb + lower_components + botton + bottom_housing
    if is_defective(overall):
        defective += 1
print(defective, 1 - defective/total)

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions