0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

モンテカルロ法によるπの計算

Last updated at Posted at 2023-01-23

pythonでモンテカルロ法によるπの計算をします。これが本当のMonty Python.

πを求めるアルゴリズム

monte.py
#!/usr/bin/python3
import os
import binascii
import random

# 乱数の種を初期化
f=open("/dev/random",'rb') # /dev/randomを開く
random32bitdata=f.read(4) # 4バイト読み出し
f.close() # /dev/randomを閉じる
randomhex=binascii.hexlify(random32bitdata) #16進の文字列に変換
randomseed=int(randomhex,16) # 整数に変換
random.seed(randomseed) # ランダムシードを初期化

count=0
n=10000000
for i in range(n):
  x = random.random()
  y = random.random()
  z = x*x + y*y
  count+=1 if (z<1) else 0

print(count/n*4) 
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?