Scientific and engineering applications require precise mathematical calculations beyond basic arithmetic. The math module provides functions for powers, roots, trigonometry, and rounding that handle edge cases correctly and match mathematical standards.

Special Functions

Additional mathematical functions:

basic.py
# Basic math operations

import math

# Basic operations
# Absolute value (built-in)
print("Absolute value:")
print("abs(-5):", abs(-5))
print("abs(-3.14):", abs(-3.14))
print("abs(7):", abs(7))

# Power
print("\nPower:")
print("pow(2, 3):", pow(2, 3))
print("2 ** 3:", 2 ** 3)
print("math.pow(2, 3):", math.pow(2, 3))
print("pow(5, 2):", pow(5, 2))
print("pow(2, 10):", pow(2, 10))

# Square root
print("\nSquare root:")
print("math.sqrt(16):", math.sqrt(16))
print("math.sqrt(2):", math.sqrt(2))
print("math.sqrt(100):", math.sqrt(100))
print("math.sqrt(0.25):", math.sqrt(0.25))

# Cube root
print("\nCube root:")
print("math.pow(8, 1/3):", math.pow(8, 1/3))
print("8 ** (1/3):", 8 ** (1/3))
print("27 ** (1/3):", 27 ** (1/3))

# Max and min (built-in)
print("\nMax and min:")
print("max(5, 10):", max(5, 10))
print("min(5, 10):", min(5, 10))
print("max(-3, -7):", max(-3, -7))
print("min(3.14, 2.71):", min(3.14, 2.71))
print("max([5, 2, 9, 1]):", max([5, 2, 9, 1]))

# Exponential and logarithm
print("\nExponential and logarithm:")
print("math.exp(1):", math.exp(1))           # e^1
print("math.exp(2):", math.exp(2))           # e^2
print("math.log(math.e):", math.log(math.e)) # ln(e) = 1
print("math.log10(100):", math.log10(100))   # log base 10
print("math.log2(8):", math.log2(8))         # log base 2

# Constants
print("\nMath constants:")
print("math.pi:", math.pi)
print("math.e:", math.e)
print("math.tau:", math.tau)  # 2π
print("math.inf:", math.inf)
print("math.nan:", math.nan)

# Factorial
print("\nFactorial:")
print("math.factorial(5):", math.factorial(5))
print("math.factorial(10):", math.factorial(10))

# GCD and LCM
print("\nGCD and LCM:")
print("math.gcd(12, 8):", math.gcd(12, 8))
print("math.gcd(100, 75):", math.gcd(100, 75))
print("math.lcm(12, 8):", math.lcm(12, 8))  # Python 3.9+
print("math.lcm(4, 6, 8):", math.lcm(4, 6, 8))

# Practical examples
print("\nPractical examples:")

# Distance
x1, y1 = 0, 0
x2, y2 = 3, 4
distance = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
print(f"Distance from ({x1},{y1}) to ({x2},{y2}): {distance}")

# Circle area
radius = 
area = math.pi * radius**2
print(f"Circle area (r={radius}): {area:.2f}")

# Compound interest
principal = 1000
rate = 0.05
years = 10
amount = principal * (1 + rate)**years
print(f"Compound interest: ${amount:.2f}")

# Combinations
print("\nCombinations:")
n, k = 5, 2
combinations = math.factorial(n) // (math.factorial(k) * math.factorial(n - k))
print(f"C({n},{k}) = {combinations}")
print(f"math.comb({n},{k}) = {math.comb(n, k)}")  # Python 3.8+

# Permutations
permutations = math.factorial(n) // math.factorial(n - k)
print(f"P({n},{k}) = {permutations}")
print(f"math.perm({n},{k}) = {math.perm(n, k)}")  # Python 3.8+

# Basic math operations

import math

# Basic operations
# Absolute value (built-in)
print("Absolute value:")
print("abs(-5):", abs(-5))
print("abs(-3.14):", abs(-3.14))
print("abs(7):", abs(7))

# Power
print("\nPower:")
print("pow(2, 3):", pow(2, 3))
print("2 ** 3:", 2 ** 3)
print("math.pow(2, 3):", math.pow(2, 3))
print("pow(5, 2):", pow(5, 2))
print("pow(2, 10):", pow(2, 10))

# Square root
print("\nSquare root:")
print("math.sqrt(16):", math.sqrt(16))
print("math.sqrt(2):", math.sqrt(2))
print("math.sqrt(100):", math.sqrt(100))
print("math.sqrt(0.25):", math.sqrt(0.25))

# Cube root
print("\nCube root:")
print("math.pow(8, 1/3):", math.pow(8, 1/3))
print("8 ** (1/3):", 8 ** (1/3))
print("27 ** (1/3):", 27 ** (1/3))

# Max and min (built-in)
print("\nMax and min:")
print("max(5, 10):", max(5, 10))
print("min(5, 10):", min(5, 10))
print("max(-3, -7):", max(-3, -7))
print("min(3.14, 2.71):", min(3.14, 2.71))
print("max([5, 2, 9, 1]):", max([5, 2, 9, 1]))

# Exponential and logarithm
print("\nExponential and logarithm:")
print("math.exp(1):", math.exp(1))           # e^1
print("math.exp(2):", math.exp(2))           # e^2
print("math.log(math.e):", math.log(math.e)) # ln(e) = 1
print("math.log10(100):", math.log10(100))   # log base 10
print("math.log2(8):", math.log2(8))         # log base 2

# Constants
print("\nMath constants:")
print("math.pi:", math.pi)
print("math.e:", math.e)
print("math.tau:", math.tau)  # 2π
print("math.inf:", math.inf)
print("math.nan:", math.nan)

# Factorial
print("\nFactorial:")
print("math.factorial(5):", math.factorial(5))
print("math.factorial(10):", math.factorial(10))

# GCD and LCM
print("\nGCD and LCM:")
print("math.gcd(12, 8):", math.gcd(12, 8))
print("math.gcd(100, 75):", math.gcd(100, 75))
print("math.lcm(12, 8):", math.lcm(12, 8))  # Python 3.9+
print("math.lcm(4, 6, 8):", math.lcm(4, 6, 8))

# Practical examples
print("\nPractical examples:")

# Distance
x1, y1 = 0, 0
x2, y2 = 3, 4
distance = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
print(f"Distance from ({x1},{y1}) to ({x2},{y2}): {distance}")

# Circle area
radius = 
area = math.pi * radius**2
print(f"Circle area (r={radius}): {area:.2f}")

# Compound interest
principal = 1000
rate = 0.05
years = 10
amount = principal * (1 + rate)**years
print(f"Compound interest: ${amount:.2f}")

# Combinations
print("\nCombinations:")
n, k = 5, 2
combinations = math.factorial(n) // (math.factorial(k) * math.factorial(n - k))
print(f"C({n},{k}) = {combinations}")
print(f"math.comb({n},{k}) = {math.comb(n, k)}")  # Python 3.8+

# Permutations
permutations = math.factorial(n) // math.factorial(n - k)
print(f"P({n},{k}) = {permutations}")
print(f"math.perm({n},{k}) = {math.perm(n, k)}")  # Python 3.8+

# Basic math operations

import math

# Basic operations
# Absolute value (built-in)
print("Absolute value:")
print("abs(-5):", abs(-5))
print("abs(-3.14):", abs(-3.14))
print("abs(7):", abs(7))

# Power
print("\nPower:")
print("pow(2, 3):", pow(2, 3))
print("2 ** 3:", 2 ** 3)
print("math.pow(2, 3):", math.pow(2, 3))
print("pow(5, 2):", pow(5, 2))
print("pow(2, 10):", pow(2, 10))

# Square root
print("\nSquare root:")
print("math.sqrt(16):", math.sqrt(16))
print("math.sqrt(2):", math.sqrt(2))
print("math.sqrt(100):", math.sqrt(100))
print("math.sqrt(0.25):", math.sqrt(0.25))

# Cube root
print("\nCube root:")
print("math.pow(8, 1/3):", math.pow(8, 1/3))
print("8 ** (1/3):", 8 ** (1/3))
print("27 ** (1/3):", 27 ** (1/3))

# Max and min (built-in)
print("\nMax and min:")
print("max(5, 10):", max(5, 10))
print("min(5, 10):", min(5, 10))
print("max(-3, -7):", max(-3, -7))
print("min(3.14, 2.71):", min(3.14, 2.71))
print("max([5, 2, 9, 1]):", max([5, 2, 9, 1]))

# Exponential and logarithm
print("\nExponential and logarithm:")
print("math.exp(1):", math.exp(1))           # e^1
print("math.exp(2):", math.exp(2))           # e^2
print("math.log(math.e):", math.log(math.e)) # ln(e) = 1
print("math.log10(100):", math.log10(100))   # log base 10
print("math.log2(8):", math.log2(8))         # log base 2

# Constants
print("\nMath constants:")
print("math.pi:", math.pi)
print("math.e:", math.e)
print("math.tau:", math.tau)  # 2π
print("math.inf:", math.inf)
print("math.nan:", math.nan)

# Factorial
print("\nFactorial:")
print("math.factorial(5):", math.factorial(5))
print("math.factorial(10):", math.factorial(10))

# GCD and LCM
print("\nGCD and LCM:")
print("math.gcd(12, 8):", math.gcd(12, 8))
print("math.gcd(100, 75):", math.gcd(100, 75))
print("math.lcm(12, 8):", math.lcm(12, 8))  # Python 3.9+
print("math.lcm(4, 6, 8):", math.lcm(4, 6, 8))

# Practical examples
print("\nPractical examples:")

# Distance
x1, y1 = 0, 0
x2, y2 = 3, 4
distance = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
print(f"Distance from ({x1},{y1}) to ({x2},{y2}): {distance}")

# Circle area
radius = 
area = math.pi * radius**2
print(f"Circle area (r={radius}): {area:.2f}")

# Compound interest
principal = 1000
rate = 0.05
years = 10
amount = principal * (1 + rate)**years
print(f"Compound interest: ${amount:.2f}")

# Combinations
print("\nCombinations:")
n, k = 5, 2
combinations = math.factorial(n) // (math.factorial(k) * math.factorial(n - k))
print(f"C({n},{k}) = {combinations}")
print(f"math.comb({n},{k}) = {math.comb(n, k)}")  # Python 3.8+

# Permutations
permutations = math.factorial(n) // math.factorial(n - k)
print(f"P({n},{k}) = {permutations}")
print(f"math.perm({n},{k}) = {math.perm(n, k)}")  # Python 3.8+

rounding.py
# Rounding operations

import math

# Rounding operations
value = 3.7

print("Value:", value)
print()

# Round (built-in)
print("round():")
print("round(3.7):", round(3.7))     # 4
print("round(3.4):", round(3.4))     # 3
print("round(3.5):", round(3.5))     # 4 (banker's rounding)
print("round(2.5):", round(2.5))     # 2 (banker's rounding)
print("round(-3.5):", round(-3.5))   # -4
print("round(-3.6):", round(-3.6))   # -4

# Round to decimals
print("\nRound to decimals:")
pi = math.pi
print("Original:", pi)
print("round(pi, 2):", round(pi, 2))
print("round(pi, 4):", round(pi, 4))
print("round(pi, 0):", round(pi, 0))

# Ceil (round up)
print("\nmath.ceil() - round up:")
print("ceil(3.1):", math.ceil(3.1))     # 4
print("ceil(3.9):", math.ceil(3.9))     # 4
print("ceil(-3.1):", math.ceil(-3.1))   # -3
print("ceil(5.0):", math.ceil(5.0))     # 5

# Floor (round down)
print("\nmath.floor() - round down:")
print("floor(3.1):", math.floor(3.1))   # 3
print("floor(3.9):", math.floor(3.9))   # 3
print("floor(-3.1):", math.floor(-3.1)) # -4
print("floor(5.0):", math.floor(5.0))   # 5

# Trunc (toward zero)
print("\nmath.trunc() - toward zero:")
print("trunc(3.9):", math.trunc(3.9))   # 3
print("trunc(-3.9):", math.trunc(-3.9)) # -3
print("int(3.9):", int(3.9))            # 3 (same as trunc)

# Compare all methods
print("\nCompare rounding methods:")
test_values = [2.3, 2.5, 2.7, -2.3, -2.5, -2.7]

print("Value\tFloor\tRound\tCeil\tTrunc")
for v in test_values:
    print(f"{v}\t{math.floor(v)}\t{round(v)}\t{math.ceil(v)}\t{math.trunc(v)}")

# Practical examples
print("\nPractical examples:")

# Calculate pages needed
items = 47
items_per_page = 10
pages = math.ceil(items / items_per_page)
print(f"{items} items, {items_per_page} per page = {pages} pages")

# Round money
price = 19.996
rounded = round(price, 2)
print(f"Price ${price} rounded: ${rounded}")

# Nearest multiple
number = 47
multiple = 10
nearest = round(number / multiple) * multiple
print(f"{number} to nearest {multiple}: {nearest}")

# Division with rounding
print("\nDivision with rounding:")
print("7 // 2 (floor):", 7 // 2)
print("round(7 / 2):", round(7 / 2))
print("ceil(7 / 2):", math.ceil(7 / 2))

# Banker's rounding
print("\nBanker's rounding (round half to even):")
print("round(0.5):", round(0.5))  # 0
print("round(1.5):", round(1.5))  # 2
print("round(2.5):", round(2.5))  # 2
print("round(3.5):", round(3.5))  # 4

# Custom rounding
def round_up(n, decimals=0):
    """Always round up"""
    multiplier = 10 ** decimals
    return math.ceil(n * multiplier) / multiplier

def round_down(n, decimals=0):
    """Always round down"""
    multiplier = 10 ** decimals
    return math.floor(n * multiplier) / multiplier

print("\nCustom rounding:")
val = 3.14159
print(f"round_up({val}, 2):", round_up(val, 2))
print(f"round_down({val}, 2):", round_down(val, 2))

# Significant figures
def round_sig(x, sig=2):
    """Round to significant figures"""
    if x == 0:
        return 0
    return round(x, -int(math.floor(math.log10(abs(x)))) + (sig - 1))

print("\nSignificant figures:")
print("round_sig(12345, 2):", round_sig(12345, 2))
print("round_sig(0.012345, 2):", round_sig(0.012345, 2))

trigonometry.py
# Trigonometric functions

import math

# Trigonometric functions
# Angles in radians
angle = math.pi / 4  # 45 degrees

print(f"Angle: {angle} radians (45 degrees)")
print()

# Basic trig functions
print("Basic trigonometry:")
print(f"sin(π/4): {math.sin(angle)}")
print(f"cos(π/4): {math.cos(angle)}")
print(f"tan(π/4): {math.tan(angle)}")

# Common angles
print("\nCommon angles:")
print(f"sin(0): {math.sin(0)}")
print(f"sin(π/2): {math.sin(math.pi / 2)}")  # 90 degrees
print(f"sin(π): {math.sin(math.pi)}")        # 180 degrees
print(f"cos(0): {math.cos(0)}")
print(f"cos(π): {math.cos(math.pi)}")

# Inverse trig functions
print("\nInverse trigonometry:")
print(f"asin(1): {math.asin(1)}")            # π/2
print(f"acos(0): {math.acos(0)}")            # π/2
print(f"atan(1): {math.atan(1)}")            # π/4
print(f"atan2(1, 1): {math.atan2(1, 1)}")    # π/4

# Hyperbolic functions
print("\nHyperbolic functions:")
print(f"sinh(1): {math.sinh(1)}")
print(f"cosh(1): {math.cosh(1)}")
print(f"tanh(1): {math.tanh(1)}")

# Degree/radian conversion
print("\nDegree/radian conversion:")
degrees = 45
radians = math.radians(degrees)
print(f"{degrees} degrees = {radians} radians")
print(f"{radians} radians = {math.degrees(radians)} degrees")

# Trig with degrees
print("\nTrig with degrees (convert first):")
angle45 = math.radians(45)
angle90 = math.radians(90)
print(f"sin(45°): {math.sin(angle45)}")
print(f"cos(90°): {math.cos(angle90)}")

# Practical examples
print("\nPractical examples:")

# Right triangle
adjacent = 3
opposite = 4
hypotenuse = math.sqrt(adjacent**2 + opposite**2)
angle_rad = math.atan2(opposite, adjacent)
angle_deg = math.degrees(angle_rad)

print(f"Right triangle ({adjacent}, {opposite}, ?):")
print(f"Hypotenuse: {hypotenuse}")
print(f"Angle: {angle_deg:.2f} degrees")

# Circle point
radius = 10
angle_circle = math.radians(60)
x = radius * math.cos(angle_circle)
y = radius * math.sin(angle_circle)
print(f"\nPoint on circle (r={radius}, 60°):")
print(f"x: {x:.2f}")
print(f"y: {y:.2f}")

# Distance and angle between points
x1, y1 = 0, 0
x2, y2 = 3, 3
distance = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
angle_to_point = math.degrees(math.atan2(y2 - y1, x2 - x1))

print(f"\nFrom ({x1},{y1}) to ({x2},{y2}):")
print(f"Distance: {distance:.2f}")
print(f"Angle: {angle_to_point:.2f} degrees")

# Table of sine values
print("\nSine values (0° to 90°, step 15°):")
for deg in range(0, 91, 15):
    rad = math.radians(deg)
    print(f"{deg:3}°: {math.sin(rad):.4f}")

# Verify Pythagorean identity
print("\nPythagorean identity (sin²x + cos²x = 1):")
test_angles = [0, math.pi/6, math.pi/4, math.pi/3, math.pi/2]
for ang in test_angles:
    result = math.sin(ang)**2 + math.cos(ang)**2
    print(f"angle={ang:.4f}: sin²+cos² = {result:.10f}")

# Unit circle
print("\nUnit circle (radius=1):")
for deg in range(0, 360, 45):
    rad = math.radians(deg)
    x = math.cos(rad)
    y = math.sin(rad)
    print(f"{deg:3}°: ({x:6.3f}, {y:6.3f})")

comparison.py
# Comparison and clamping

import math

# Comparison operations
# Max and min (built-in)
print("Max and min:")
print("max(5, 10):", max(5, 10))
print("min(5, 10):", min(5, 10))
print("max(-5, -10):", max(-5, -10))
print("min(3.14, 2.71):", min(3.14, 2.71))

# Max/min of multiple values
print("\nMax/min of multiple:")
numbers = [5, 2, 9, 1, 7, 3]
print("List:", numbers)
print("Max:", max(numbers))
print("Min:", min(numbers))

# With key function
words = ['apple', 'pie', 'a', 'cherry']
print("\nWords:", words)
print("Longest:", max(words, key=len))
print("Shortest:", min(words, key=len))

# Clamp (restrict to range)
def clamp(value, min_val, max_val):
    """Clamp value to range [min_val, max_val]"""
    return max(min_val, min(max_val, value))

print("\nClamp to range [0, 100]:")
print("clamp(-10, 0, 100):", clamp(-10, 0, 100))
print("clamp(50, 0, 100):", clamp(50, 0, 100))
print("clamp(150, 0, 100):", clamp(150, 0, 100))

# Sign
print("\nSign (copysign):")
print("math.copysign(5, 1):", math.copysign(5, 1))
print("math.copysign(5, -1):", math.copysign(5, -1))
print("math.copysign(-5, 1):", math.copysign(-5, 1))

# Custom sign function
def sign(x):
    """Return sign of number (-1, 0, or 1)"""
    if x > 0:
        return 1
    elif x < 0:
        return -1
    else:
        return 0

print("\nSign function:")
print("sign(5):", sign(5))
print("sign(-5):", sign(-5))
print("sign(0):", sign(0))

# Absolute difference
print("\nAbsolute difference:")
print("|5 - 10|:", abs(5 - 10))
print("|10 - 5|:", abs(10 - 5))
print("|-5 - (-10)|:", abs(-5 - (-10)))

# Within tolerance
def within_tolerance(a, b, tol):
    """Check if values are within tolerance"""
    return abs(a - b) <= tol

print("\nWithin tolerance:")
a = 3.14159
b = 3.14
tolerance = 0.01
print(f"{a} ≈ {b} (±{tolerance}): {within_tolerance(a, b, tolerance)}")

# Practical examples
print("\nPractical examples:")

# Keep score in bounds
score = 150
bounded = clamp(score, 0, 100)
print(f"Score {score} bounded to [0,100]: {bounded}")

# Volume control
volume = 1.5
valid_volume = clamp(volume, 0.0, 1.0)
print(f"Volume {volume} clamped to [0,1]: {valid_volume}")

# Temperature range
temp = -5
min_temp = 0
max_temp = 30
valid_temp = clamp(temp, min_temp, max_temp)
print(f"Temp {temp}° bounded to [{min_temp},{max_temp}]: {valid_temp}")

# Find range
values = [23, 45, 12, 67, 34]
min_val = min(values)
max_val = max(values)
range_val = max_val - min_val
print(f"\nValues: {values}")
print(f"Range: {min_val} to {max_val} (span: {range_val})")

# Midpoint
def midpoint(a, b):
    """Calculate midpoint between two values"""
    return (a + b) / 2

print("\nMidpoint:")
print("Between 10 and 20:", midpoint(10, 20))
print("Between -5 and 15:", midpoint(-5, 15))

# Compare with tolerance
print("\nFloat comparison:")
print("0.1 + 0.2 == 0.3:", 0.1 + 0.2 == 0.3)
print("isclose(0.1 + 0.2, 0.3):", math.isclose(0.1 + 0.2, 0.3))

# Multiple comparisons
print("\nmath.isclose():")
print("isclose(1.0, 1.0001):", math.isclose(1.0, 1.0001))
print("isclose(1.0, 1.0001, abs_tol=0.001):", math.isclose(1.0, 1.0001, abs_tol=0.001))
print("isclose(1.0, 1.01, rel_tol=0.01):", math.isclose(1.0, 1.01, rel_tol=0.01))

# Find index of max/min
print("\nIndex of max/min:")
values = [5, 2, 9, 1, 7]
print("Values:", values)
print("Index of max:", values.index(max(values)))
print("Index of min:", values.index(min(values)))

special.py
# Special functions

import math

# Special functions
# Hypotenuse
print("Hypotenuse:")
print("math.hypot(3, 4):", math.hypot(3, 4))
print("math.hypot(5, 12):", math.hypot(5, 12))
print("math.hypot(1, 1):", math.hypot(1, 1))

# Hypotenuse in N dimensions
print("\nHypotenuse (N dimensions):")
print("hypot(3, 4, 12):", math.hypot(3, 4, 12))
print("hypot(1, 1, 1):", math.hypot(1, 1, 1))

# Expm1 (exp(x) - 1) - accurate for small x
print("\nExpm1 (e^x - 1):")
print("math.expm1(0):", math.expm1(0))
print("math.expm1(1):", math.expm1(1))
print("math.expm1(0.001):", math.expm1(0.001))

# Log1p (log(1 + x)) - accurate for small x
print("\nLog1p (ln(1 + x)):")
print("math.log1p(0):", math.log1p(0))
print("math.log1p(1):", math.log1p(1))
print("math.log1p(0.001):", math.log1p(0.001))

# Distance formula
print("\nDistance (math.dist):")
p1 = (0, 0)
p2 = (3, 4)
print(f"dist({p1}, {p2}):", math.dist(p1, p2))

p3 = (1, 2, 3)
p4 = (4, 6, 8)
print(f"dist({p3}, {p4}):", math.dist(p3, p4))

# Remainder
print("\nRemainder:")
print("math.remainder(10, 3):", math.remainder(10, 3))
print("10 % 3:", 10 % 3)
print("math.remainder(10.5, 3):", math.remainder(10.5, 3))

# Modulo vs remainder
print("\nModulo vs Remainder:")
print("7 % 3:", 7 % 3)
print("remainder(7, 3):", math.remainder(7, 3))
print("-7 % 3:", -7 % 3)
print("remainder(-7, 3):", math.remainder(-7, 3))

# FMod (modulo as in C)
print("\nfmod (C-style modulo):")
print("math.fmod(10, 3):", math.fmod(10, 3))
print("math.fmod(-10, 3):", math.fmod(-10, 3))

# Prod (product of iterable) - Python 3.8+
print("\nProduct:")
numbers = [2, 3, 4]
print(f"prod({numbers}):", math.prod(numbers))
print("prod([1, 2, 3, 4, 5]):", math.prod([1, 2, 3, 4, 5]))

# Sum with start value
print("\nSum:")
print("sum([1, 2, 3]):", sum([1, 2, 3]))
print("sum([1, 2, 3], 10):", sum([1, 2, 3], 10))

# Fsum (accurate floating-point sum)
print("\nfsum (accurate sum):")
values = [0.1] * 10
print(f"sum({values}):", sum(values))
print(f"fsum({values}):", math.fsum(values))

# Special values
print("\nSpecial values:")
print("inf:", math.inf)
print("-inf:", -math.inf)
print("nan:", math.nan)

# Check special values
print("\nCheck special values:")
print("isinf(math.inf):", math.isinf(math.inf))
print("isnan(math.nan):", math.isnan(math.nan))
print("isfinite(100):", math.isfinite(100))
print("isfinite(math.inf):", math.isfinite(math.inf))

# NextAfter - Python 3.9+
print("\nNextAfter:")
try:
    print("nextafter(1.0, 2.0):", math.nextafter(1.0, 2.0))
    print("nextafter(1.0, 0.0):", math.nextafter(1.0, 0.0))
except AttributeError:
    print("(nextafter requires Python 3.9+)")

# Ulp - Python 3.9+
print("\nUlp (unit in last place):")
try:
    print("ulp(1.0):", math.ulp(1.0))
    print("ulp(10.0):", math.ulp(10.0))
except AttributeError:
    print("(ulp requires Python 3.9+)")

# Practical examples
print("\nPractical examples:")

# Calculate hypotenuse without overflow
a = 1e100
b = 1e100
hypot = math.hypot(a, b)
print(f"Hypotenuse of very large sides: {hypot}")

# Accurate small calculations
small = 0.0001
exp_result = math.expm1(small)
log_result = math.log1p(small)
print(f"expm1({small}): {exp_result}")
print(f"log1p({small}): {log_result}")

# Accurate sum
values = [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]
regular_sum = sum(values)
accurate_sum = math.fsum(values)
print(f"Regular sum: {regular_sum}")
print(f"Accurate sum: {accurate_sum}")
print(f"Expected: 1.0")

# Product calculation
discount_factors = [0.9, 0.95, 0.98]
final_multiplier = math.prod(discount_factors)
price = 100
final_price = price * final_multiplier
print(f"\nSequential discounts: {discount_factors}")
print(f"Final multiplier: {final_multiplier:.4f}")
print(f"Price ${price} -> ${final_price:.2f}")

math module Python's standard library for mathematical functions including trigonometry, logarithms, and constants like pi and e.
ceil and floor ceil() rounds up to the nearest integer, floor() rounds down - essential for inventory counts, pagination, and resource allocation.
isclose() Compares floats with tolerance to avoid precision errors - use instead of == for float comparisons.

Exercise: practical.py

Calculate distance between two points and determine if values are within tolerance