Pi Day의 π 계산

Mar 15 2023
해피 파이 데이! 저는 데이터 과학 채널에 π를 추정하는 똑똑하고, 멍청하고, 진지하고, 재미있고, 창의적이거나, 지루한 방법을 묻는 글을 올렸습니다. 돌아온 결과는 다음과 같습니다. Vinicius Aurichio Eric Silberstein Tom Dinitz ChatGPT(Conor Dowling 제공) 1002자리가 인쇄되고 마지막 2자리가 잘못되었지만 공정하게 1000자리만 요청했습니다.

해피 파이 데이! 저는 데이터 과학 채널에 π를 추정하는 똑똑하고, 멍청하고, 진지하고, 재미있고, 창의적이거나, 지루한 방법을 묻는 글을 올렸습니다. 돌아온 내용은 ​​다음과 같습니다.

비니시우스 오리치오

(6*sum(1/n**2 for n in range(1, 1001)))**(0.5)

=> 3.1406380562059946

에릭 실버스타인

import numpy as np
delta = 1e-9
4 * delta * np.sum((1 - np.arange(0, 1, delta) ** 2) ** 0.5)

=> 3.1415926555897618

톰 디니츠

import numpy as np
n = 100_000_000
5 - 4 * np.mean(np.round(np.random.rand(n)/np.random.rand(n)) % 2 == 0)

=> 3.14152348

      
                

M = 1_000_000
2 * np.product([4 * (k**2) / (4 * (k**2)-1) for k in range(1,M)])

=> 3.1415918681913633

      
                

import numpy as np
n = 100_000_000
4 * np.sum((np.random.rand(n) ** 2 + np.random.rand(n) ** 2) ** 0.5 < 1) / n

=> 3.14188724

ChatGPT(코너 다울링 제공)

그것은 1002자리를 인쇄하고 마지막 2자리는 틀렸지만 공정하게 1000자리만 요청했습니다.

트리스탄 밀스

m1 = 1.0
m2 = 10_000_000_000
m_sum = (m1 + m2)
mu = (m1 - m2)/m_sum

V1, v2 = 0., 1.

collisions = 0

while not (v1 <= 0 and v2 < 0 and abs(v1) <= abs(v2)):
   collisions += 1
   if collisions % 2:
       v1, v2 = mu * v1 + 2*m2/m_sum*v2, -mu * v2 + 2*m1/m_sum*v1
   else:
       v1 = -v1

print(collisions)

=> 314159

크리스티나 데드릭

조회 테이블. 어떤 유형의 메모리에 π 값을 저장합니다. 필요할 때 요청하십시오. 컴퓨터가 없는 경우 이 책을 구입하는 것을 고려하십시오 . 지갑에 보관된 처음 10자리의 인쇄물도 꽤 멀리 갈 수 있습니다.

같은 정신으로 누군가에게 물어볼 수 있습니다.

아추 발라수브라마니안

def calculate_pi(n, i=1):
    return n if i == n else (2 * i - 1) + (i ** 2 / calculate_pi(n, i +1))

4 / calculate_pi(24)

=> 3.141592653589793

      
                

닉 하트만

from getch import getch
from mpmath import mp, pi
mp.dps = 1000

starting_prompt = "Guess the digits of pi!  What comes next after 3.14"
starting_digit = 4

current_prompt = starting_prompt
current_digit = starting_digit
high_score = 0
while True:
    print(current_prompt)
    target_digit = str(pi)[current_digit]
    guessed_digit = getch()
    if guessed_digit == target_digit:
        current_prompt += guessed_digit
        current_digit += 1
    else:
        if current_digit > high_score:
            high_score = current_digit
        print(f"""
              Incorrect!  The next digit was {target_digit}.
              You guessed {current_digit-2} digits after the decimal point. 
              Your high score is {high_score-2}. 
            
              Press 'y' to play again or any other key to exit
            """)
        if getch().lower() == "y":
            current_prompt = starting_prompt
            current_digit = starting_digit
        else:
            break

웨인 코번

이것을보세요:

마이클 로손

import numpy as np
from math import pi
from sklearn.linear_model import LinearRegression

MAX_RADIUS = 100
MIN_RADIUS = 0.1
NUM_CIRCLES_TO_MEASURE = 200

# set random number seed for replicability
np.random.seed(seed=314)

# calculate the true values of radius-squared and area
radii = np.random.uniform(low=MIN_RADIUS, high=MAX_RADIUS, size=NUM_CIRCLES_TO_MEASURE)
radii_squared = np.square(radii)
areas = pi * radii_squared

# add Gaussian noise to areas (simulating measurement area)
areas_with_measurement_error = areas + np.random.normal(loc=0, scale=15)

# fit linear regression to find value of pi
radii_squared_preprocessed_array = radii_squared.reshape(-1, 1)
linear_model = LinearRegression()
linear_model.fit(X=radii_squared_preprocessed_array, y=areas_with_measurement_error)
pi_derived = linear_model.coef_
print("The value of pi, calculated via linear regression assuming Gaussian errors, is ", pi_derived)

=> The value of pi, calculated via linear regression assuming Gaussian errors, is  [3.14159265]

마이클 로손

from math import pi

def point_estimator_of_real_number(num):
   return 3

estimated_pi = point_estimator_of_real_number(pi)

print("The value of pi estimated by the Lawsonian 3-Estimator is", estimated_pi)

=> The value of pi estimated by the Lawsonian 3-Estimator is 3

저는 그 아이디어를 이 특정 추정 문제에 적용했습니다. 그리고 여러분이 알고 있는 것이 있습니다. Lawsonian 3-Estimator는 실제로 파이 계산을 꽤 잘합니다!

2 * pi를 계산하도록 요청하지 마십시오.

데이비드 러스티그

파이를 근사화하는 가장 좋아하는 방법 중 하나는 Buffon의 바늘 문제에서 나옵니다. 요약된 역사로서 우리는 Buffon이 길이( l) 의 바늘(또는 성냥이나 바게트 또는 1차원)을 설정된 너비(t)만큼 떨어진 평행선이 있는 바닥에 미친 듯이 떨어뜨리고 있다고 상상할 수 있습니다. 선을 넘는 바늘. 그는 인내심이 부족하여 대신 이 질문을 제기하는 논문과 대신 적분 기하학을 사용하는 솔루션을 출판하기로 결정합니다. 증명 은 중간 길이이며 합리적인 수학을 사용하므로 이 문제에 대한 해결책은 다음과 같습니다.

p =2/π * l/t

Buffon과 달리 우리는 성냥을 떨어뜨리는 데 절대 지루하지 않은 컴퓨터를 가지고 있으므로 다음과 같이 시뮬레이션할 수 있습니다.

A) 패키지 가져오기 및 "바닥:" 만들기

import cmath
import math
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from IPython.display import display

fig = plt.figure()
ax = plt.subplot()
ax.set_ylim([0, 20])
ax.set_xlim([0, 20])
for i in range(2, 20, 2):
    plt.axvline(x=i, color='blue')
ax.set_xticks(range(2, 20, 2))
ax.set_yticks([])
plt.title('A beautifully striped floor')

      
                

def drop_match(x_bounds, y_bounds, match_length, ax):
    x_start = np.random.uniform(x_bounds[0], x_bounds[1])
    y_start = np.random.uniform(y_bounds[0], y_bounds[1])
    pt = cmath.rect(match_length, math.radians(np.random.uniform(0, 360)))
    x_end = pt.real + x_start
    y_end = pt.imag + y_start
    ax.plot([x_start, x_end], [y_start, y_end])
    return [x_start, x_end]

def check_match(xcoords, lines):
    inside = 0
    for line in lines:
        if min(xcoords) < line and max(xcoords) > line:
            inside = 1
    return inside

fig = plt.figure(figsize=(10,5))
fig.set_facecolor('white')
ax = plt.subplot()
ax.set_ylim([0, 20])
ax.set_xlim([0, 20])
for i in range(2, 20, 2):
    plt.axvline(x=i, color='blue')
ax.set_xticks(range(2, 20, 2))
ax.set_yticks([])
match_counter = 0
match_cross_line_counter = 0
pi_approximations = []
for i in range(10000):
    coords = drop_match([2, 18], [2,18], 2, ax)
    match_counter += 1
    match_cross_line_counter += check_match(coords, range(2, 20, 2))
    pi_approx = 2/(match_cross_line_counter/match_counter)
    pi_approximations.append(pi_approx)
plt.title(f'A beautifully striped floor with {match_counter} matches.  Pi Approximation: {pi_approx}')
display(fig)

      
                

fig = plt.figure(figsize=(10,5))
sns.lineplot(x=range(len(pi_approximations)), y=pi_approximations)
plt.xlabel('Num Matches')
plt.ylabel('Pi Approximation')
plt.axhline(np.pi, linestyle = '--')
plt.title('Pi Approximation by number of matches')
plt.legend(['Approximation', 'Pi'])

      
                

Pi Day에서 Pi와 데이터 과학에 대해 이야기하는 Dave Xiao