-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Description
阮老师的博客里有一篇蒙特卡洛的入门文章 ,这里附上其中3个python源码。
例子
计算π
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)
计算厚度
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)