📜  pi (1)

📅  最后修改于: 2023-12-03 15:33:41.336000             🧑  作者: Mango

Pi

Pi symbol

Pi (π) is a mathematical constant that represents the ratio of a circle's circumference to its diameter, approximately equal to 3.14159. It is an irrational number, meaning it cannot be expressed accurately as a finite decimal or fraction. Pi has fascinated mathematicians, scientists, and engineers for centuries and continues to inspire new discoveries today.

History

The ancient Egyptians and Babylonians both approximated the value of pi around 1900–1600 BCE. The Greek mathematician Archimedes (c. 287–212 BCE) is credited with the first accurate estimation of pi using the method of exhaustion, which involves inscribing and circumscribing polygons around a circle. In the 18th century, mathematicians began using infinite series to calculate pi to more decimal places. Today, computers have calculated pi to trillions of digits.

Pi in Programming

Pi is often used in programming for calculations involving circles and spheres. Virtually every programming language has a built-in constant for pi, usually called PI or π. In many programming languages, pi can be called using the Math.PI or math.pi function.

Examples

In JavaScript:

const diameter = 10;
const circumference = diameter * Math.PI;
console.log(circumference);  // Output: 31.41592653589793

In Python:

import math

radius = 5
area = math.pi * radius ** 2
print(area)  # Output: 78.53981633974483
Pi Approximations

There are many different ways to approximate pi to greater and greater accuracy. One of the simplest is the Monte Carlo method, which involves randomly selecting points within a square and calculating how many of them fall inside a circle inscribed within the square. The ratio of points inside the circle to total points can be used to calculate pi to increasing decimal places.

Example

In Python:

import random
import math

inside_circle = 0
total_points = 100000

for i in range(total_points):
    x = random.uniform(-1, 1)
    y = random.uniform(-1, 1)
    if math.sqrt(x**2 + y**2) <= 1:
        inside_circle += 1

pi_estimate = 4 * inside_circle / total_points
print(pi_estimate)  # Output: 3.14252
Conclusion

Pi is a fascinating mathematical constant with a rich history and many applications in programming and beyond. Whether you're calculating the circumference of a circle or exploring the mysteries of the universe, pi is an essential tool.