開発環境
- OS X El Capitan - Apple (OS)
- Emacs (Text Editor)
- Python 3.5 (プログラミング言語)
Doing Math with Python: Use Programming to Explore Algebra, Statistics, Calculus, and More! (Amit Saha (著)、No Starch Press)のChapter 5.(Playing with Sets and Probability)、Programming Challenges #5: Estimating the Area of a Circle, π(No. 3664)を解いてみる。
#5: Estimating the Area of a Circle, π(No. 3664)
コード(Emacs)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import random
import math
RADIUS = 2
def area_of_circle(num):
n = 0
for _ in range(num):
x = random.uniform(0, 2 * RADIUS)
y = random.uniform(0, 2 * RADIUS)
if abs((RADIUS - x)**2 + (RADIUS - y)**2) <= RADIUS**2:
n += 1
return (2 * RADIUS) ** 2 * n / num
# estimating the value of pi
def pi(radius, num):
n = 0
for _ in range(num):
x = random.uniform(0, 2 * radius)
y = random.uniform(0, 2 * radius)
if abs((radius - x)**2 + (radius - y)**2) <= radius**2:
n += 1
return 4 * n / num
if __name__ == '__main__':
print('Radius: {0}'.format(RADIUS))
AREA = RADIUS**2 * math.pi
nums = [10**3, 10**5, 10**6]
for n in nums:
print('Area: {0}, Estimated ({1} darts): {2})'.format(
AREA, n, area_of_circle(n)))
print('π: {0}'.format(math.pi))
for r in range(1, 6):
print('Radius: {0}'.format(r))
for n in nums:
print('Estimated ({0}): {1}'.format(n, pi(r, n)))
入出力結果(Terminal, IPython)
$ ./sample5.py Radius: 2 Area: 12.566370614359172, Estimated (1000 darts): 12.576) Area: 12.566370614359172, Estimated (100000 darts): 12.60672) Area: 12.566370614359172, Estimated (1000000 darts): 12.573664) π: 3.141592653589793 Radius: 1 Estimated (1000): 3.12 Estimated (100000): 3.14028 Estimated (1000000): 3.143084 Radius: 2 Estimated (1000): 3.212 Estimated (100000): 3.14244 Estimated (1000000): 3.141948 Radius: 3 Estimated (1000): 3.068 Estimated (100000): 3.15572 Estimated (1000000): 3.141496 Radius: 4 Estimated (1000): 3.216 Estimated (100000): 3.13848 Estimated (1000000): 3.140504 Radius: 5 Estimated (1000): 3.136 Estimated (100000): 3.14436 Estimated (1000000): 3.142588 $
0 コメント:
コメントを投稿