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.

Python3: モンテカルロ法で円周率を求める

Posted at

こちらのページを参考にしました。
モンテカルロ法で円周率を求めるのをPythonで実装

プログラム

pi_monte_carlo.py
#! /usr/bin/python
#
import random
import math
# ------------------------------------------------------------------
def calc_pi_proc(nn):
	point = 0
	for it in range(nn):
		xx = random.random()
		yy = random.random()
		if math.hypot(xx,yy) < 1.0:
			point += 1
	pi = 4.0 * point / nn
#
	return	pi
#
# ------------------------------------------------------------------
for it in range (1,11):
	nn = 1000 * (it**2)
	pi = calc_pi_proc(nn)
	print(it,nn,pi)
#
# ------------------------------------------------------------------

実行結果

乱数を使うので、実行のたびに結果が異なります。

$ ./pi_monte_carlo.py 
1 1000 3.196
2 4000 3.118
3 9000 3.1542222222222223
4 16000 3.14175
5 25000 3.13312
6 36000 3.145
7 49000 3.1484897959183673
8 64000 3.1285625
9 81000 3.1404938271604936
10 100000 3.14424
$ ./pi_monte_carlo.py 
1 1000 3.124
2 4000 3.151
3 9000 3.1355555555555554
4 16000 3.14675
5 25000 3.14496
6 36000 3.1384444444444446
7 49000 3.134612244897959
8 64000 3.151
9 81000 3.1486913580246916
10 100000 3.13892

確認したバージョン

$ python --version
Python 3.10.7
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?