乱数

モジュールのインポート

import numpy as np  
import random
import matplotlib.pyplot as plt
import scienceplots
#Warning : As of version 2.0.0, you need to add import scienceplots before setting the style (plt.style.use('science')).
plt.style.use(['science', 'notebook'])

関数 random

https://numpy.org/doc/stable/reference/random/generated/numpy.random.random.html
n = 6
print(f"{'x':>15s} {'y':>15s}")
for i in range(n):
    print(f"{random.random():15.10f} {random.random():15.10f}")
x               y
0.1692870693    0.5355835547
0.3285543176    0.5886628553
0.9149056063    0.3778905228
0.0160303602    0.7148574067
0.7984849726    0.7698328851
0.7007923555    0.3388337840
n2 = 600000
bmin, bmax = 0.0, 6.0
print(f"{'#1':>6s} {'#2':>6s} {'#3':>6s} {'#4':>6s} {'#5':>6s} {'#6':>6s} {'total':>6s}")
k = np.zeros(n)
for i in range(n2):
    z = random.uniform(bmin, bmax)
    iz = np.ceil(z)
    for j in range(6):
        if iz==j+1:
            k[j] = k[j]+1
print(f"{k[0]:6.0f} {k[1]:6.0f} {k[2]:6.0f} {k[3]:6.0f} {k[4]:6.0f} {k[5]:6.0f} {np.sum(k):6.0f}")
    #1     #2     #3     #4     #5     #6  total
100330 100234  99800 100263  99510  99863 600000

乱数による円周率の計算

n3 = 2000
c_min, c_max = -1.0, 1.0
m = 0
xx = np.empty(0)
yy = np.empty(0)
for i in range(n3):
    xx = np.append(xx, random.uniform(c_min, c_max))
    yy = np.append(yy, random.uniform(c_min, c_max))
    r = np.sqrt(xx[i]**2+yy[i]**2)
    if r <= 1.0:
        m = m+1
p = float(m)/n3*4.0
print("pi:",np.pi)
print("p :",p)
q = 180.0/np.pi
n4 = 361
th = np.linspace(0.0, 360.0/q, n4)
ct = np.cos(th)
st = np.sin(th)
pi: 3.141592653589793
p : 3.128
fig = plt.figure() # グラフ領域の作成
plt.axes().set_aspect('equal')
plt.xlabel(r"$x$") # x軸のラベル設定
plt.ylabel(r"$y$") # y軸のラベル設定
plt.xlim(-1.0, 1.0) # x軸範囲の設定
plt.ylim(-1.0, 1.0) # y軸範囲の設定
plt.plot(xx, yy,'.')
plt.plot(ct, st)
fig.savefig('p1_ex08_1.pdf')