2023-02-03

How to generate PI (3.14) from the Gregory-Leibniz's formula

#!/usr/bin/env python3
# ---------------------------------------
# Project Name : PythonCheatSheet
# File Name    : Calculate-Pi-3-Gregory-Leibniz.py
# Created Date : 2023-02-02 12:46:25 UTC+7
# Last Modified: 2023-02-02 12:48:49 UTC+7
# ---------------------------------------
from pytictoc import TicToc
t = TicToc()  # create TicToc instance
t.tic()       # Start timer
print(f"================================")
# DO SOMETHING
# https://www.mathscareers.org.uk/calculating-pi/
# Gregory-Leibniz:
# Pi/4 = [1 - 1/3 + 1/5 - 1/7 + 1/9 - ...]

def my_pi(p_number: int) -> float:
    my_result = 0
    for i in range(1, n+1, 1):
        if i % 2 == 0:  # even
            my_result = my_result - 1/(2*i - 1)
        else:           # odd
            my_result = my_result + 1/(2*i - 1)
    return my_result*4


n = 1000000
print(f'my_pi({n}): {my_pi(n)}')

print(f"================================")
t.toc()       # Print elapsed time: "Elapsed time is <xxx> seconds."
# ---------------------------------------
# REF:
# https://mathshistory.st-andrews.ac.uk/HistTopics/1000_places/
# 3.14159265358979323846264338327950288419716939937510

# RESULT:
# WINDOWS 3900x:
# ================================
# my_pi(1.000.000): 3.1415916535897743
# ================================
# Elapsed time is 0.127023 seconds.



# Linux 3900x:
# ================================
# PI     : 3.1415916535897743
# ================================
# Elapsed time is 0.209464 seconds.
# ================================
# PI     : 3.1415916535897743
# ================================
# Elapsed time is 0.197258 seconds



# LINUX 5600g:
# n = 100  # 3.1315929035585537
# n = 500  # 3.139592655589785
# n = 700  # 3.1401640828900845
# n = 1.000  # 3.140592653839794
# n = 2.000  # 3.1410926536210413
# n = 3.000  # 3.1412593202657186
# n = 5.000  # 3.141392653591791    - 0.001042 seconds.
# n = 1.000.000   # 3.1415916535897743  - 0.074705 seconds.
# n = 10.000.000  # 3.1415925535897915  - 0.757600 seconds.
# n = 100.000.000 # 3.141592643589326   - 7.646685 seconds.
# n = 1.000.000.000     # 3.1415926525880504 - 81.178900 seconds.
# n = 1.000.000.000     # 3.1415926525880504 - 76.741032 seconds
# n = 10.000.000.000    # 3.141592653488346  - 937.967539 seconds.

No comments:

Post a Comment