Introduction to Python’s math Module: Using Constants Like Pi, e, and Functions

When creating programs for scientific calculations or geometry, mathematical constants like Pi ($\pi$) and Euler’s number ($e$) are frequently used.

Python’s standard math module allows you to use these constants with high precision. It also provides advanced mathematical functions such as square roots and trigonometric functions.

This article explains the main constants provided by the math module and provides implementation examples.

目次

List of Major Mathematical Constants

Here are the representative constants defined in the math module.

Constant NameSymbolValue (Approx.)Meaning
math.pi$\pi$3.141592…Pi. Used for calculating circle circumference and area.
math.e$e$2.718281…Euler’s number (Napier’s constant). Used for exponential and logarithmic functions.
math.tau$\tau$6.283185…Tau ($2\pi$). Twice the value of Pi.
math.inf$\infty$infInfinity (positive). Same as float('inf').
math.nanNaNnanNot a Number. Indicates an undefined calculation result.

Practical Usage Examples

1. Geometric Calculation: Pi (math.pi)

Here is a program that calculates the circumference and area of a circle from its radius.

import math

def calculate_circle_properties(radius):
    """
    Function to calculate circumference and area from radius
    """
    # Circumference = 2 * π * r
    circumference = 2 * math.pi * radius
    
    # Area = π * r^2
    area = math.pi * (radius ** 2)
    
    return circumference, area

# Circle with radius 5.0
r = 5.0
circ, area = calculate_circle_properties(r)

print(f"Radius: {r}")
print(f"Circumference: {circ:.4f}")
print(f"Area: {area:.4f}")

Execution Result:

Radius: 5.0
Circumference: 31.4159
Area: 78.5398

2. Exponential Calculation: Euler’s Number (math.e)

Here is an example using Euler’s number to simulate exponential growth (such as an approximation of compound interest).

import math

def exponential_growth(initial_value, rate, time):
    """
    Continuous compound interest formula: A = P * e^(rt)
    """
    return initial_value * (math.e ** (rate * time))

# Initial value 100, growth rate 5% (0.05), time 10 units
result = exponential_growth(100, 0.05, 10)

print(f"Value after growth: {result:.4f}")

Execution Result:

Value after growth: 164.8721

3. Infinity (math.inf) and Not a Number (math.nan)

These are often used to represent specific boundary conditions or error states in numerical calculations.

import math

# Comparison with infinity
positive_infinity = math.inf
print(f"Larger than 10 to the power of 100?: {positive_infinity > 10**100}")

# Operations using infinity
# Adding anything to infinity results in infinity
print(f"inf + 100: {positive_infinity + 100}")

# Checking Not a Number (NaN)
not_a_number = math.nan
print(f"Type of NaN: {type(not_a_number)}")

# Check using math.isnan() (Do not compare with ==)
print(f"Is it NaN?: {math.isnan(not_a_number)}")

Execution Result:

Larger than 10 to the power of 100?: True
inf + 100: inf
Type of NaN: <class 'float'>
Is it NaN?: True

Commonly Used Mathematical Functions

In addition to constants, the math module includes many useful functions.

  • math.sqrt(x): Returns the square root ($\sqrt{x}$).
  • math.gcd(a, b): Returns the greatest common divisor.
  • math.floor(x): Rounds down to the nearest integer.
  • math.ceil(x): Rounds up to the nearest integer.
  • math.sin(x), math.cos(x): Trigonometric functions (specified in radians).
import math

# Square root
print(f"Square root of 25: {math.sqrt(25)}")

# Greatest Common Divisor (GCD of 12 and 18 is 6)
print(f"GCD(12, 18): {math.gcd(12, 18)}")

# Ceiling and Floor
value = 3.7
print(f"Ceil: {math.ceil(value)}")
print(f"Floor: {math.floor(value)}")

Execution Result:

Square root of 25: 5.0
GCD(12, 18): 6
Ceil: 4
Floor: 3

Summary

  • Load the module with import math.
  • Using constants like math.pi and math.e enables high-precision calculations.
  • Special values like math.inf (infinity) and math.nan (not a number) are also provided.
  • Utilizing functions like sqrt and gcd allows you to write complex calculation logic concisely.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次