원주율이란?
π = Pi = circumference / diameter = 3.14
구하는 방법
이집트나 바빌로니아에서 최초의 원주율을 바퀴를 직접 굴려 구했다고 한다.
우리가 잘 아는 기원은, 기원 전 250년 경 아르키메데스가 원에 내접 / 외접하는 96각형과 닮은 삼각형의 공식을 이용, 이의 둘레가 원의 둘레와 비슷할 것이라는 가정 하에 약 "3.14163"정도로 구한 것이다.
그 뒤엔 공식을 통해 원주율을 구하는 아주 다양한 방법이 나왔다. 밑의 두 개 링크 참조.
누가 뭐래도 나는 나무위키가 좋다 - namu.wiki/w/%EC%9B%90%EC%A3%BC%EC%9C%A8/%EC%97%AD%EC%82%AC
수학 관련 블로그 - www.mathscareers.org.uk/calculating-pi/
Calculating Pi (π) - Maths Careers
Pi is central to mathematics. Calculating pi can be achieved by different methods. Ancient and modern methods can be used to calculate PI
www.mathscareers.org.uk
파이썬 구현
1. math.pi 사용
가장 쉬운 방법은 아무래도 Python의 math library에 있는 pi() function을 사용하는 것이겠다.
math library
docs.python.org/3/library/math.html
math — Mathematical functions — Python 3.9.1rc1 documentation
math — Mathematical functions This module provides access to the mathematical functions defined by the C standard. These functions cannot be used with complex numbers; use the functions of the same name from the cmath module if you require support for co
docs.python.org
import math
pi = str(math.pi)
num_digits = -1
while num_digits not in (0,15):
num_digits = int(input("How many digits of PI do you want?: (0-15)"))
print(pi[:num_digits+2])
노트
` 다만 math.pi로는 3.141592653589793 (소숫점 15자리) 까지만 나온다.
` Python float(실수)은 64비트 double-precision 베이스이고,
base-2 fraction으로 1/2^n의 합으로 소숫점 자리들이 표시된다(*).
` 이에 해당하는 Significand precision / 부동 소숫점 / 유효숫자 비트는 53비트이기에(**),
2^(-53) = 1.10 x 10^(-16), 15 - 17자리까지만 소숫점이 표시되는 것이다.
* www.geeksforgeeks.org/python-float-type-and-its-methods/
** en.wikipedia.org/wiki/Double-precision_floating-point_format
따라서 더 많은 소수자리수를 표시하기 위해서는 다른 알고리즘을 써야할 것이다.
2. mpmath 라이브러리 사용
검색하다가 찾게 되었다...!
소스코드 - stackoverflow.com/questions/9004789/1000-digits-of-pi-in-python
mpmath는 mpf (Real Float) 라는 Python의 built-in float과 비슷한 숫자형태를 제공한다.
mp라는 object로 정확도 / precision을 정하게 되는데, mp.prec으로는 binary precision을, mp.dps 로는 decimal (소숫점)one을 정할 수 있다.
mpmath documentation 참고 - mpmath.org.doc/current/basics.html
3. pi 구현 다른 알고리즘 사용
stackoverflow.com/questions/231767/what-does-the-yield-keyword-do
파이의 값은 다른 수학적 알고리즘으로도 구할 수 있다.
이 링크의 예시는 각 자릿수를 구하는 알고리즘을 통해, string list에 각 자릿수를 append하여 전체 파이값을 구한다.
그리고 결과값 (string list)를 출력!
'프로젝트들 > Python_Udemy' 카테고리의 다른 글
[Python]15 - Tax Calculator 미국 도시 세금 계산기 (0) | 2020.12.24 |
---|---|
[Python]20 - Coin Flip Simulator 동전 던지기 (0) | 2020.12.22 |
[Python]3 - Fibonacci Sequence 피보나치 수열 (0) | 2020.12.08 |
[Python]9 - 이진수 (Binary) & 십진수 (Decimal) 컨버터 (0) | 2020.12.08 |
[Python]8 - Change Return 거스름돈 구하기 (0) | 2020.12.02 |
댓글