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.

math module Python's standard library for mathematical functions including trigonometry, logarithms, and constants like pi and e.

Basic Operations

The math module provides power and root functions:

radius
basic.py
Replay: real traced execution (multi-file project)
# 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 = 5
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 = 2
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 = 10
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+

  1. x1 ← 0, y1 ← 0, x2 ← 3, y2 ← 4, distance ← 5.0, radius ← 5, area ← 78.53981633974483

    6# Absolute value (built-in)7print("Absolute value:")8print("abs(-5):", abs(-5))9print("abs(-3.14):", abs(-3.14))10print("abs(7):", abs(7))1112# Power13print("\nPower:")14print("pow(2, 3):", pow(2, 3))15print("2 ** 3:", 2 ** 3)16print("math.pow(2, 3):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.pow(2, 3))17print("pow(5, 2):", pow(5, 2))18print("pow(2, 10):", pow(2, 10))1920# Square root21print("\nSquare root:")22print("math.sqrt(16):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.sqrt(16))23print("math.sqrt(2):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.sqrt(2))24print("math.sqrt(100):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.sqrt(100))25print("math.sqrt(0.25):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.sqrt(0.25))2627# Cube root28print("\nCube root:")29print("math.pow(8, 1/3):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.pow(8, 1/3))30print("8 ** (1/3):", 8 ** (1/3))31print("27 ** (1/3):", 27 ** (1/3))3233# Max and min (built-in)34print("\nMax and min:")35print("max(5, 10):", max(5, 10))36print("min(5, 10):", min(5, 10))37print("max(-3, -7):", max(-3, -7))38print("min(3.14, 2.71):", min(3.14, 2.71))39print("max([5, 2, 9, 1]):", max([5, 2, 9, 1]))4041# Exponential and logarithm42print("\nExponential and logarithm:")43print("math.exp(1):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.exp(1))           # e^144print("math.exp(2):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.exp(2))           # e^245print("math.log(math.e):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.log(math.e2.718281828459045)) # ln(e) = 146print("math.log10(100):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.log10(100))   # log base 1047print("math.log2(8):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.log2(8))         # log base 24849# Constants50print("\nMath constants:")51print("math.pi:", math.pi3.141592653589793)52print("math.e:", math.e2.718281828459045)53print("math.tau:", math.tau6.283185307179586)  # 2π54print("math.inf:", math.infinf)55print("math.nan:", math.nannan)5657# Factorial58print("\nFactorial:")59print("math.factorial(5):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.factorial(5))60print("math.factorial(10):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.factorial(10))6162# GCD and LCM63print("\nGCD and LCM:")64print("math.gcd(12, 8):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.gcd(12, 8))65print("math.gcd(100, 75):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.gcd(100, 75))66print("math.lcm(12, 8):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.lcm(12, 8))  # Python 3.9+67print("math.lcm(4, 6, 8):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.lcm(4, 6, 8))6869# Practical examples70print("\nPractical examples:")7172# Distance73x1→ 0, y1→ 0 = 0, 074x2→ 3, y2→ 4 = 3, 475distance→ 5.0 = math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.sqrt((x23 - x10)**2 + (y24 - y10)**2)76print(f"Distance from ({x10},{y10}) to ({x23},{y24}): {distance5.0}")7778# Circle area79radius→ 5 = 5  #@radius=2, 1080area→ 78.53981633974483 = math.pi3.141592653589793 * radius5**281print(f"Circle area (r={radius5}): {area78.53981633974483:.2f}")8283# Compound interest84principal→ 1000 = 100085rate→ 0.05 = 0.0586years→ 10 = 1087amount→ 1628.894626777442 = principal1000 * (1 + rate0.05)**years1088print(f"Compound interest: ${amount1628.894626777442:.2f}")8990# Combinations91print("\nCombinations:")92n→ 5, k→ 2 = 5, 293combinations→ 10 = math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.factorial(n5) // (math.factorial(k2) * math.factorial(n - k))94print(f"C({n5},{k2}) = {combinations10}")95print(f"math.comb({n5},{k2}) = {math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.comb(n, k)}")  # Python 3.8+9697# Permutations98permutations→ 20 = math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.factorial(n5) // math.factorial(n - k2)99print(f"P({n5},{k2}) = {permutations20}")100print(f"math.perm({n5},{k2}) = {math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.perm(n, k)}")  # Python 3.8+
    outputAbsolute value:
    abs(-5): 5
    abs(-3.14): 3.14
    abs(7): 7
    
    Power:
    pow(2, 3): 8
    2 ** 3: 8
    math.pow(2, 3): 8.0
    pow(5, 2): 25
    pow(2, 10): 1024
    
    Square root:
    math.sqrt(16): 4.0
    math.sqrt(2): 1.4142135623730951
    math.sqrt(100): 10.0
    math.sqrt(0.25): 0.5
    
    Cube root:
    math.pow(8, 1/3): 2.0
    8 ** (1/3): 2.0
    27 ** (1/3): 3.0
    
    Max and min:
    max(5, 10): 10
    min(5, 10): 5
    max(-3, -7): -3
    min(3.14, 2.71): 2.71
    max([5, 2, 9, 1]): 9
    
    Exponential and logarithm:
    math.exp(1): 2.718281828459045
    math.exp(2): 7.38905609893065
    math.log(math.e): 1.0
    math.log10(100): 2.0
    math.log2(8): 3.0
    
    Math constants:
    math.pi: 3.141592653589793
    math.e: 2.718281828459045
    math.tau: 6.283185307179586
    math.inf: inf
    math.nan: nan
    
    Factorial:
    math.factorial(5): 120
    math.factorial(10): 3628800
    
    GCD and LCM:
    math.gcd(12, 8): 4
    math.gcd(100, 75): 25
    math.lcm(12, 8): 24
    math.lcm(4, 6, 8): 24
    
    Practical examples:
    Distance from (0,0) to (3,4): 5.0
    Circle area (r=5): 78.54
    Compound interest: $1628.89
    
    Combinations:
    C(5,2) = 10
    math.comb(5,2) = 10
    P(5,2) = 20
    math.perm(5,2) = 20
  1. x1 ← 0, y1 ← 0, x2 ← 3, y2 ← 4, distance ← 5.0, radius ← 2, area ← 12.566370614359172

    6# Absolute value (built-in)7print("Absolute value:")8print("abs(-5):", abs(-5))9print("abs(-3.14):", abs(-3.14))10print("abs(7):", abs(7))1112# Power13print("\nPower:")14print("pow(2, 3):", pow(2, 3))15print("2 ** 3:", 2 ** 3)16print("math.pow(2, 3):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.pow(2, 3))17print("pow(5, 2):", pow(5, 2))18print("pow(2, 10):", pow(2, 10))1920# Square root21print("\nSquare root:")22print("math.sqrt(16):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.sqrt(16))23print("math.sqrt(2):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.sqrt(2))24print("math.sqrt(100):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.sqrt(100))25print("math.sqrt(0.25):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.sqrt(0.25))2627# Cube root28print("\nCube root:")29print("math.pow(8, 1/3):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.pow(8, 1/3))30print("8 ** (1/3):", 8 ** (1/3))31print("27 ** (1/3):", 27 ** (1/3))3233# Max and min (built-in)34print("\nMax and min:")35print("max(5, 10):", max(5, 10))36print("min(5, 10):", min(5, 10))37print("max(-3, -7):", max(-3, -7))38print("min(3.14, 2.71):", min(3.14, 2.71))39print("max([5, 2, 9, 1]):", max([5, 2, 9, 1]))4041# Exponential and logarithm42print("\nExponential and logarithm:")43print("math.exp(1):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.exp(1))           # e^144print("math.exp(2):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.exp(2))           # e^245print("math.log(math.e):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.log(math.e2.718281828459045)) # ln(e) = 146print("math.log10(100):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.log10(100))   # log base 1047print("math.log2(8):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.log2(8))         # log base 24849# Constants50print("\nMath constants:")51print("math.pi:", math.pi3.141592653589793)52print("math.e:", math.e2.718281828459045)53print("math.tau:", math.tau6.283185307179586)  # 2π54print("math.inf:", math.infinf)55print("math.nan:", math.nannan)5657# Factorial58print("\nFactorial:")59print("math.factorial(5):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.factorial(5))60print("math.factorial(10):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.factorial(10))6162# GCD and LCM63print("\nGCD and LCM:")64print("math.gcd(12, 8):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.gcd(12, 8))65print("math.gcd(100, 75):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.gcd(100, 75))66print("math.lcm(12, 8):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.lcm(12, 8))  # Python 3.9+67print("math.lcm(4, 6, 8):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.lcm(4, 6, 8))6869# Practical examples70print("\nPractical examples:")7172# Distance73x1→ 0, y1→ 0 = 0, 074x2→ 3, y2→ 4 = 3, 475distance→ 5.0 = math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.sqrt((x23 - x10)**2 + (y24 - y10)**2)76print(f"Distance from ({x10},{y10}) to ({x23},{y24}): {distance5.0}")7778# Circle area79radius→ 2 = 280area→ 12.566370614359172 = math.pi3.141592653589793 * radius2**281print(f"Circle area (r={radius2}): {area12.566370614359172:.2f}")8283# Compound interest84principal→ 1000 = 100085rate→ 0.05 = 0.0586years→ 10 = 1087amount→ 1628.894626777442 = principal1000 * (1 + rate0.05)**years1088print(f"Compound interest: ${amount1628.894626777442:.2f}")8990# Combinations91print("\nCombinations:")92n→ 5, k→ 2 = 5, 293combinations→ 10 = math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.factorial(n5) // (math.factorial(k2) * math.factorial(n - k))94print(f"C({n5},{k2}) = {combinations10}")95print(f"math.comb({n5},{k2}) = {math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.comb(n, k)}")  # Python 3.8+9697# Permutations98permutations→ 20 = math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.factorial(n5) // math.factorial(n - k2)99print(f"P({n5},{k2}) = {permutations20}")100print(f"math.perm({n5},{k2}) = {math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.perm(n, k)}")  # Python 3.8+
    outputAbsolute value:
    abs(-5): 5
    abs(-3.14): 3.14
    abs(7): 7
    
    Power:
    pow(2, 3): 8
    2 ** 3: 8
    math.pow(2, 3): 8.0
    pow(5, 2): 25
    pow(2, 10): 1024
    
    Square root:
    math.sqrt(16): 4.0
    math.sqrt(2): 1.4142135623730951
    math.sqrt(100): 10.0
    math.sqrt(0.25): 0.5
    
    Cube root:
    math.pow(8, 1/3): 2.0
    8 ** (1/3): 2.0
    27 ** (1/3): 3.0
    
    Max and min:
    max(5, 10): 10
    min(5, 10): 5
    max(-3, -7): -3
    min(3.14, 2.71): 2.71
    max([5, 2, 9, 1]): 9
    
    Exponential and logarithm:
    math.exp(1): 2.718281828459045
    math.exp(2): 7.38905609893065
    math.log(math.e): 1.0
    math.log10(100): 2.0
    math.log2(8): 3.0
    
    Math constants:
    math.pi: 3.141592653589793
    math.e: 2.718281828459045
    math.tau: 6.283185307179586
    math.inf: inf
    math.nan: nan
    
    Factorial:
    math.factorial(5): 120
    math.factorial(10): 3628800
    
    GCD and LCM:
    math.gcd(12, 8): 4
    math.gcd(100, 75): 25
    math.lcm(12, 8): 24
    math.lcm(4, 6, 8): 24
    
    Practical examples:
    Distance from (0,0) to (3,4): 5.0
    Circle area (r=2): 12.57
    Compound interest: $1628.89
    
    Combinations:
    C(5,2) = 10
    math.comb(5,2) = 10
    P(5,2) = 20
    math.perm(5,2) = 20
  1. x1 ← 0, y1 ← 0, x2 ← 3, y2 ← 4, distance ← 5.0, radius ← 10, area ← 314.1592653589793

    6# Absolute value (built-in)7print("Absolute value:")8print("abs(-5):", abs(-5))9print("abs(-3.14):", abs(-3.14))10print("abs(7):", abs(7))1112# Power13print("\nPower:")14print("pow(2, 3):", pow(2, 3))15print("2 ** 3:", 2 ** 3)16print("math.pow(2, 3):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.pow(2, 3))17print("pow(5, 2):", pow(5, 2))18print("pow(2, 10):", pow(2, 10))1920# Square root21print("\nSquare root:")22print("math.sqrt(16):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.sqrt(16))23print("math.sqrt(2):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.sqrt(2))24print("math.sqrt(100):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.sqrt(100))25print("math.sqrt(0.25):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.sqrt(0.25))2627# Cube root28print("\nCube root:")29print("math.pow(8, 1/3):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.pow(8, 1/3))30print("8 ** (1/3):", 8 ** (1/3))31print("27 ** (1/3):", 27 ** (1/3))3233# Max and min (built-in)34print("\nMax and min:")35print("max(5, 10):", max(5, 10))36print("min(5, 10):", min(5, 10))37print("max(-3, -7):", max(-3, -7))38print("min(3.14, 2.71):", min(3.14, 2.71))39print("max([5, 2, 9, 1]):", max([5, 2, 9, 1]))4041# Exponential and logarithm42print("\nExponential and logarithm:")43print("math.exp(1):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.exp(1))           # e^144print("math.exp(2):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.exp(2))           # e^245print("math.log(math.e):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.log(math.e2.718281828459045)) # ln(e) = 146print("math.log10(100):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.log10(100))   # log base 1047print("math.log2(8):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.log2(8))         # log base 24849# Constants50print("\nMath constants:")51print("math.pi:", math.pi3.141592653589793)52print("math.e:", math.e2.718281828459045)53print("math.tau:", math.tau6.283185307179586)  # 2π54print("math.inf:", math.infinf)55print("math.nan:", math.nannan)5657# Factorial58print("\nFactorial:")59print("math.factorial(5):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.factorial(5))60print("math.factorial(10):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.factorial(10))6162# GCD and LCM63print("\nGCD and LCM:")64print("math.gcd(12, 8):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.gcd(12, 8))65print("math.gcd(100, 75):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.gcd(100, 75))66print("math.lcm(12, 8):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.lcm(12, 8))  # Python 3.9+67print("math.lcm(4, 6, 8):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.lcm(4, 6, 8))6869# Practical examples70print("\nPractical examples:")7172# Distance73x1→ 0, y1→ 0 = 0, 074x2→ 3, y2→ 4 = 3, 475distance→ 5.0 = math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.sqrt((x23 - x10)**2 + (y24 - y10)**2)76print(f"Distance from ({x10},{y10}) to ({x23},{y24}): {distance5.0}")7778# Circle area79radius→ 10 = 1080area→ 314.1592653589793 = math.pi3.141592653589793 * radius10**281print(f"Circle area (r={radius10}): {area314.1592653589793:.2f}")8283# Compound interest84principal→ 1000 = 100085rate→ 0.05 = 0.0586years→ 10 = 1087amount→ 1628.894626777442 = principal1000 * (1 + rate0.05)**years1088print(f"Compound interest: ${amount1628.894626777442:.2f}")8990# Combinations91print("\nCombinations:")92n→ 5, k→ 2 = 5, 293combinations→ 10 = math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.factorial(n5) // (math.factorial(k2) * math.factorial(n - k))94print(f"C({n5},{k2}) = {combinations10}")95print(f"math.comb({n5},{k2}) = {math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.comb(n, k)}")  # Python 3.8+9697# Permutations98permutations→ 20 = math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.factorial(n5) // math.factorial(n - k2)99print(f"P({n5},{k2}) = {permutations20}")100print(f"math.perm({n5},{k2}) = {math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.perm(n, k)}")  # Python 3.8+
    outputAbsolute value:
    abs(-5): 5
    abs(-3.14): 3.14
    abs(7): 7
    
    Power:
    pow(2, 3): 8
    2 ** 3: 8
    math.pow(2, 3): 8.0
    pow(5, 2): 25
    pow(2, 10): 1024
    
    Square root:
    math.sqrt(16): 4.0
    math.sqrt(2): 1.4142135623730951
    math.sqrt(100): 10.0
    math.sqrt(0.25): 0.5
    
    Cube root:
    math.pow(8, 1/3): 2.0
    8 ** (1/3): 2.0
    27 ** (1/3): 3.0
    
    Max and min:
    max(5, 10): 10
    min(5, 10): 5
    max(-3, -7): -3
    min(3.14, 2.71): 2.71
    max([5, 2, 9, 1]): 9
    
    Exponential and logarithm:
    math.exp(1): 2.718281828459045
    math.exp(2): 7.38905609893065
    math.log(math.e): 1.0
    math.log10(100): 2.0
    math.log2(8): 3.0
    
    Math constants:
    math.pi: 3.141592653589793
    math.e: 2.718281828459045
    math.tau: 6.283185307179586
    math.inf: inf
    math.nan: nan
    
    Factorial:
    math.factorial(5): 120
    math.factorial(10): 3628800
    
    GCD and LCM:
    math.gcd(12, 8): 4
    math.gcd(100, 75): 25
    math.lcm(12, 8): 24
    math.lcm(4, 6, 8): 24
    
    Practical examples:
    Distance from (0,0) to (3,4): 5.0
    Circle area (r=10): 314.16
    Compound interest: $1628.89
    
    Combinations:
    C(5,2) = 10
    math.comb(5,2) = 10
    P(5,2) = 20
    math.perm(5,2) = 20

Rounding Functions

Different rounding strategies for various use cases:

rounding.py
Replay: real traced execution (multi-file project)
# 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))

  1. value ← 3.7, pi ← 3.141592653589793, test_values ← [2.3, 2.5, 2.7, -2.3, -2.5, -2.7]

    5# Rounding operations6value→ 3.7 = 3.778print("Value:", value3.7)9print()1011# Round (built-in)12print("round():")13print("round(3.7):", round(3.7))     # 414print("round(3.4):", round(3.4))     # 315print("round(3.5):", round(3.5))     # 4 (banker's rounding)16print("round(2.5):", round(2.5))     # 2 (banker's rounding)17print("round(-3.5):", round(-3.5))   # -418print("round(-3.6):", round(-3.6))   # -41920# Round to decimals21print("\nRound to decimals:")22pi→ 3.141592653589793 = math.pi3.14159265358979323print("Original:", pi3.141592653589793)24print("round(pi, 2):", round(pi3.141592653589793, 2))25print("round(pi, 4):", round(pi3.141592653589793, 4))26print("round(pi, 0):", round(pi3.141592653589793, 0))2728# Ceil (round up)29print("\nmath.ceil() - round up:")30print("ceil(3.1):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.ceil(3.1))     # 431print("ceil(3.9):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.ceil(3.9))     # 432print("ceil(-3.1):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.ceil(-3.1))   # -333print("ceil(5.0):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.ceil(5.0))     # 53435# Floor (round down)36print("\nmath.floor() - round down:")37print("floor(3.1):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.floor(3.1))   # 338print("floor(3.9):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.floor(3.9))   # 339print("floor(-3.1):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.floor(-3.1)) # -440print("floor(5.0):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.floor(5.0))   # 54142# Trunc (toward zero)43print("\nmath.trunc() - toward zero:")44print("trunc(3.9):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.trunc(3.9))   # 345print("trunc(-3.9):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.trunc(-3.9)) # -346print("int(3.9):", int(3.9))            # 3 (same as trunc)4748# Compare all methods49print("\nCompare rounding methods:")50test_values→ [2.3, 2.5, 2.7, -2.3, -2.5, -2.7] = [2.3, 2.5, 2.7, -2.3, -2.5, -2.7]5152print("Value\tFloor\tRound\tCeil\tTrunc")53for v in test_values:
    outputValue: 3.7
    round():
    round(3.7): 4
    round(3.4): 3
    round(3.5): 4
    round(2.5): 2
    round(-3.5): -4
    round(-3.6): -4
    
    Round to decimals:
    Original: 3.141592653589793
    round(pi, 2): 3.14
    round(pi, 4): 3.1416
    round(pi, 0): 3.0
    
    math.ceil() - round up:
    ceil(3.1): 4
    ceil(3.9): 4
    ceil(-3.1): -3
    ceil(5.0): 5
    
    math.floor() - round down:
    floor(3.1): 3
    floor(3.9): 3
    floor(-3.1): -4
    floor(5.0): 5
    
    math.trunc() - toward zero:
    trunc(3.9): 3
    trunc(-3.9): -3
    int(3.9): 3
    
    Compare rounding methods:
    Value	Floor	Round	Ceil	Trunc
  2. for v in test_values:

    pass 1 of 6
    52print("Value\tFloor\tRound\tCeil\tTrunc")53for v2.3 in test_values[2.3, 2.5, 2.7, -2.3, -2.5, -2.7]:54    print(f"{v2.3}\t{math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.floor(v)}\t{round(v)}\t{math.ceil(v)}\t{math.trunc(v)}")
    output2.3	2	2	3	2
    All 6 passes — pass 1 is the card above
    passv
    12.3
    22.5
    32.7
    4-2.3
    5-2.5
    6-2.7
  3. items ← 47, items_per_page ← 10, pages ← 5, price ← 19.996, rounded ← 20.0

    56# Practical examples57print("\nPractical examples:")5859# Calculate pages needed60items→ 47 = 4761items_per_page→ 10 = 1062pages→ 5 = math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.ceil(items47 / items_per_page10)63print(f"{items47} items, {items_per_page10} per page = {pages5} pages")6465# Round money66price→ 19.996 = 19.99667rounded→ 20.0 = round(price19.996, 2)68print(f"Price ${price19.996} rounded: ${rounded20.0}")6970# Nearest multiple71number→ 47 = 4772multiple→ 10 = 1073nearest→ 50 = round(number47 / multiple10) * multiple74print(f"{number47} to nearest {multiple10}: {nearest50}")7576# Division with rounding77print("\nDivision with rounding:")78print("7 // 2 (floor):", 7 // 2)79print("round(7 / 2):", round(7 / 2))80print("ceil(7 / 2):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.ceil(7 / 2))8182# Banker's rounding83print("\nBanker's rounding (round half to even):")84print("round(0.5):", round(0.5))  # 085print("round(1.5):", round(1.5))  # 286print("round(2.5):", round(2.5))  # 287print("round(3.5):", round(3.5))  # 48889# Custom rounding90def round_up(n, decimals=0):91    """Always round up"""92    multiplier = 10 ** decimals93    return math.ceil(n * multiplier) / multiplier9495def round_down(n, decimals=0):96    """Always round down"""97    multiplier = 10 ** decimals98    return math.floor(n * multiplier) / multiplier99100print("\nCustom rounding:")101val→ 3.14159 = 3.14159102print(f"round_up({val3.14159}, 2):", round_up(val, 2))103print(f"round_down({val}, 2):", round_down(val, 2))
    output
    Practical examples:
    47 items, 10 per page = 5 pages
    Price $19.996 rounded: $20.0
    47 to nearest 10: 50
    
    Division with rounding:
    7 // 2 (floor): 3
    round(7 / 2): 4
    ceil(7 / 2): 4
    
    Banker's rounding (round half to even):
    round(0.5): 0
    round(1.5): 2
    round(2.5): 2
    round(3.5): 4
    
    Custom rounding:
  4. multiplier ← 100

    89# Custom rounding90def round_up(n3.14159, decimals2=0):91    """Always round up"""92    multiplier→ 100 = 10 ** decimals293    return math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.ceil(n3.14159 * multiplier100) / multiplier
  5. print(f"round_up({val}, 2):", round_up(val, 2))

    101val = 3.14159102print(f"round_up({val3.14159}, 2):", round_up(val, 2))103print(f"round_down({val3.14159}, 2):", round_down(val, 2))
    outputround_up(3.14159, 2): 3.15
  6. multiplier ← 100

    95def round_down(n3.14159, decimals2=0):96    """Always round down"""97    multiplier→ 100 = 10 ** decimals298    return math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.floor(n3.14159 * multiplier100) / multiplier
  7. print(f"round_down({val}, 2):", round_down(val, 2))

    102print(f"round_up({val}, 2):", round_up(val, 2))103print(f"round_down({val3.14159}, 2):", round_down(val, 2))104105# Significant figures106def round_sig(x, sig=2):107    """Round to significant figures"""108    if x == 0:109        return 0110    return round(x, -int(math.floor(math.log10(abs(x)))) + (sig - 1))111112print("\nSignificant figures:")113print("round_sig(12345, 2):", round_sig(12345, 2))114print("round_sig(0.012345, 2):", round_sig(0.012345, 2))
    outputround_down(3.14159, 2): 3.14
    
    Significant figures:
  8. def round_sig(x, sig=2):

    pass 1 of 2
    105# Significant figures106def round_sig(x12345, sig2=2):107    """Round to significant figures"""108    if x == 0:109        return 0110    return round(x12345, -int(math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.floor(math.log10(abs(x)))) + (sig2 - 1))
  9. print("round_sig(12345, 2):", round_sig(12345, 2))

    112print("\nSignificant figures:")113print("round_sig(12345, 2):", round_sig(12345, 2))114print("round_sig(0.012345, 2):", round_sig(0.012345, 2))
    outputround_sig(12345, 2): 12000
  10. def round_sig(x, sig=2):

    pass 2 of 2
    105# Significant figures106def round_sig(x0.012345, sig2=2):107    """Round to significant figures"""108    if x == 0:109        return 0110    return round(x0.012345, -int(math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.floor(math.log10(abs(x)))) + (sig2 - 1))
  11. print("round_sig(0.012345, 2):", round_sig(0.012345, 2))

    113print("round_sig(12345, 2):", round_sig(12345, 2))114print("round_sig(0.012345, 2):", round_sig(0.012345, 2))
    outputround_sig(0.012345, 2): 0.012
ceil and floor ceil() rounds up to the nearest integer, floor() rounds down - essential for inventory counts, pagination, and resource allocation.

Trigonometry

Trigonometric functions work with radians:

trigonometry.py
Replay: real traced execution (multi-file project)
# 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})")

  1. angle ← 0.7853981633974483, degrees ← 45, radians ← 0.7853981633974483

    6# Angles in radians7angle→ 0.7853981633974483 = math.pi3.141592653589793 / 4  # 45 degrees89print(f"Angle: {angle0.7853981633974483} radians (45 degrees)")10print()1112# Basic trig functions13print("Basic trigonometry:")14print(f"sin(π/4): {math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.sin(angle0.7853981633974483)}")15print(f"cos(π/4): {math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.cos(angle0.7853981633974483)}")16print(f"tan(π/4): {math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.tan(angle0.7853981633974483)}")1718# Common angles19print("\nCommon angles:")20print(f"sin(0): {math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.sin(0)}")21print(f"sin(π/2): {math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.sin(math.pi3.141592653589793 / 2)}")  # 90 degrees22print(f"sin(π): {math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.sin(math.pi3.141592653589793)}")        # 180 degrees23print(f"cos(0): {math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.cos(0)}")24print(f"cos(π): {math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.cos(math.pi3.141592653589793)}")2526# Inverse trig functions27print("\nInverse trigonometry:")28print(f"asin(1): {math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.asin(1)}")            # π/229print(f"acos(0): {math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.acos(0)}")            # π/230print(f"atan(1): {math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.atan(1)}")            # π/431print(f"atan2(1, 1): {math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.atan2(1, 1)}")    # π/43233# Hyperbolic functions34print("\nHyperbolic functions:")35print(f"sinh(1): {math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.sinh(1)}")36print(f"cosh(1): {math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.cosh(1)}")37print(f"tanh(1): {math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.tanh(1)}")3839# Degree/radian conversion40print("\nDegree/radian conversion:")41degrees→ 45 = 4542radians→ 0.7853981633974483 = math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.radians(degrees45)43print(f"{degrees45} degrees = {radians0.7853981633974483} radians")44print(f"{radians0.7853981633974483} radians = {math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.degrees(radians)} degrees")4546# Trig with degrees47print("\nTrig with degrees (convert first):")48angle45→ 0.7853981633974483 = math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.radians(45)49angle90→ 1.5707963267948966 = math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.radians(90)50print(f"sin(45°): {math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.sin(angle450.7853981633974483)}")51print(f"cos(90°): {math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.cos(angle901.5707963267948966)}")5253# Practical examples54print("\nPractical examples:")5556# Right triangle57adjacent→ 3 = 358opposite→ 4 = 459hypotenuse→ 5.0 = math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.sqrt(adjacent3**2 + opposite4**2)60angle_rad→ 0.9272952180016122 = math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.atan2(opposite4, adjacent3)61angle_deg→ 53.13010235415598 = math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.degrees(angle_rad0.9272952180016122)6263print(f"Right triangle ({adjacent3}, {opposite4}, ?):")64print(f"Hypotenuse: {hypotenuse5.0}")65print(f"Angle: {angle_deg53.13010235415598:.2f} degrees")6667# Circle point68radius→ 10 = 1069angle_circle→ 1.0471975511965976 = math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.radians(60)70x→ 5.000000000000001 = radius10 * math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.cos(angle_circle1.0471975511965976)71y→ 8.660254037844386 = radius10 * math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.sin(angle_circle1.0471975511965976)72print(f"\nPoint on circle (r={radius10}, 60°):")73print(f"x: {x5.000000000000001:.2f}")74print(f"y: {y8.660254037844386:.2f}")7576# Distance and angle between points77x1→ 0, y1→ 0 = 0, 078x2→ 3, y2→ 3 = 3, 379distance→ 4.242640687119285 = math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.sqrt((x23 - x10)**2 + (y23 - y10)**2)80angle_to_point→ 45.0 = math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.degrees(math.atan2(y23 - y10, x23 - x10))8182print(f"\nFrom ({x10},{y10}) to ({x23},{y23}):")83print(f"Distance: {distance4.242640687119285:.2f}")84print(f"Angle: {angle_to_point45.0:.2f} degrees")8586# Table of sine values87print("\nSine values (0° to 90°, step 15°):")88for deg in range(0, 91, 15):
    outputAngle: 0.7853981633974483 radians (45 degrees)
    Basic trigonometry:
    sin(π/4): 0.7071067811865475
    cos(π/4): 0.7071067811865476
    tan(π/4): 0.9999999999999999
    
    Common angles:
    sin(0): 0.0
    sin(π/2): 1.0
    sin(π): 1.2246467991473532e-16
    cos(0): 1.0
    cos(π): -1.0
    
    Inverse trigonometry:
    asin(1): 1.5707963267948966
    acos(0): 1.5707963267948966
    atan(1): 0.7853981633974483
    atan2(1, 1): 0.7853981633974483
    
    Hyperbolic functions:
    sinh(1): 1.1752011936438014
    cosh(1): 1.5430806348152437
    tanh(1): 0.7615941559557649
    
    Degree/radian conversion:
    45 degrees = 0.7853981633974483 radians
    0.7853981633974483 radians = 45.0 degrees
    
    Trig with degrees (convert first):
    sin(45°): 0.7071067811865475
    cos(90°): 6.123233995736766e-17
    
    Practical examples:
    Right triangle (3, 4, ?):
    Hypotenuse: 5.0
    Angle: 53.13 degrees
    
    Point on circle (r=10, 60°):
    x: 5.00
    y: 8.66
    
    From (0,0) to (3,3):
    Distance: 4.24
    Angle: 45.00 degrees
    
    Sine values (0° to 90°, step 15°):
  2. rad ← 0.0

    pass 1 of 7
    87print("\nSine values (0° to 90°, step 15°):")88for deg0 in range(0, 91, 15):89    rad→ 0.0 = math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.radians(deg0)90    print(f"{deg0:3}°: {math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.sin(rad0.0):.4f}")
    output  0°: 0.0000
    All 7 passes — pass 1 is the card above
    passdegrad
    100.0
    2150.2617993877991494
    3300.5235987755982988
    4450.7853981633974483
    5601.0471975511965976
    6751.3089969389957472
    7901.5707963267948966
  3. test_angles ← [0, 0.5235987755982988, 0.7853981633974483, 1.0471975511965976, 1.5707963267948966]

    92# Verify Pythagorean identity93print("\nPythagorean identity (sin²x + cos²x = 1):")94test_angles→ [0, 0.5235987755982988, 0.7853981633974483, 1.0471975511965976, 1.5707963267948966] = [0, math.pi3.141592653589793/6, math.pi/4, math.pi/3, math.pi/2]95for ang in test_angles:
    output
    Pythagorean identity (sin²x + cos²x = 1):
  4. result ← 1.0

    pass 1 of 5
    94test_angles = [0, math.pi/6, math.pi/4, math.pi/3, math.pi/2]95for ang0 in test_angles[0, 0.5235987755982988, 0.7853981633974483, 1.0471975511965976, 1.5707963267948966]:96    result→ 1.0 = math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.sin(ang0)**2 + math.cos(ang)**297    print(f"angle={ang0:.4f}: sin²+cos² = {result1.0:.10f}")
    outputangle=0.0000: sin²+cos² = 1.0000000000
    All 5 passes — pass 1 is the card above
    passangresult
    101.0
    20.52359877559829881.0
    30.78539816339744831.0
    41.04719755119659761.0
    51.57079632679489661.0
  5. print(" Unit circle (radius=1):")

    99# Unit circle100print("\nUnit circle (radius=1):")101for deg in range(0, 360, 45):
    output
    Unit circle (radius=1):
  6. rad ← 0.0, x ← 1.0, y ← 0.0

    pass 1 of 8
    100print("\nUnit circle (radius=1):")101for deg0 in range(0, 360, 45):102    rad→ 0.0 = math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.radians(deg0)103    x→ 1.0 = math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.cos(rad0.0)104    y→ 0.0 = math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.sin(rad0.0)105    print(f"{deg0:3}°: ({x1.0:6.3f}, {y0.0:6.3f})")
    output  0°: ( 1.000,  0.000)
    All 8 passes — pass 1 is the card above
    passdegradxy
    100.01.00.0
    2450.78539816339744830.70710678118654760.7071067811865475
    3901.57079632679489666.123233995736766e-171.0
    41352.356194490192345-0.70710678118654750.7071067811865476
    51803.141592653589793-1.01.2246467991473532e-16
    62253.9269908169872414-0.7071067811865477-0.7071067811865475
    72704.71238898038469-1.8369701987210297e-16-1.0
    83155.4977871437821380.7071067811865474-0.7071067811865477

Comparison Functions

Comparing floating-point numbers safely:

comparison.py
Replay: real traced execution (multi-file project)
# 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)))

  1. numbers ← [5, 2, 9, 1, 7, 3], words ← ['apple', 'pie', 'a', 'cherry']

    6# Max and min (built-in)7print("Max and min:")8print("max(5, 10):", max(5, 10))9print("min(5, 10):", min(5, 10))10print("max(-5, -10):", max(-5, -10))11print("min(3.14, 2.71):", min(3.14, 2.71))1213# Max/min of multiple values14print("\nMax/min of multiple:")15numbers→ [5, 2, 9, 1, 7, 3] = [5, 2, 9, 1, 7, 3]16print("List:", numbers[5, 2, 9, 1, 7, 3])17print("Max:", max(numbers[5, 2, 9, 1, 7, 3]))18print("Min:", min(numbers[5, 2, 9, 1, 7, 3]))1920# With key function21words→ ['apple', 'pie', 'a', 'cherry'] = ['apple', 'pie', 'a', 'cherry']22print("\nWords:", words['apple', 'pie', 'a', 'cherry'])23print("Longest:", max(words['apple', 'pie', 'a', 'cherry'], key=len))24print("Shortest:", min(words['apple', 'pie', 'a', 'cherry'], key=len))2526# Clamp (restrict to range)27def clamp(value, min_val, max_val):28    """Clamp value to range [min_val, max_val]"""29    return max(min_val, min(max_val, value))3031print("\nClamp to range [0, 100]:")32print("clamp(-10, 0, 100):", clamp(-10, 0, 100))33print("clamp(50, 0, 100):", clamp(50, 0, 100))
    outputMax and min:
    max(5, 10): 10
    min(5, 10): 5
    max(-5, -10): -5
    min(3.14, 2.71): 2.71
    
    Max/min of multiple:
    List: [5, 2, 9, 1, 7, 3]
    Max: 9
    Min: 1
    
    Words: ['apple', 'pie', 'a', 'cherry']
    Longest: cherry
    Shortest: a
    
    Clamp to range [0, 100]:
  2. def clamp(value, min_val, max_val):

    pass 1 of 6
    26# Clamp (restrict to range)27def clamp(value-10, min_val0, max_val100):28    """Clamp value to range [min_val, max_val]"""29    return max(min_val0, min(max_val100, value-10))
    All 6 passes — pass 1 is the card above
    passvaluemin_valmax_val
    1-100100
    2500100
    31500100
    41500100
    51.50.01.0
    6-5030
  3. print("clamp(-10, 0, 100):", clamp(-10, 0, 100))

    31print("\nClamp to range [0, 100]:")32print("clamp(-10, 0, 100):", clamp(-10, 0, 100))33print("clamp(50, 0, 100):", clamp(50, 0, 100))34print("clamp(150, 0, 100):", clamp(150, 0, 100))
    outputclamp(-10, 0, 100): 0
  4. print("clamp(50, 0, 100):", clamp(50, 0, 100))

    32print("clamp(-10, 0, 100):", clamp(-10, 0, 100))33print("clamp(50, 0, 100):", clamp(50, 0, 100))34print("clamp(150, 0, 100):", clamp(150, 0, 100))
    outputclamp(50, 0, 100): 50
  5. print("math.copysign(5, 1):", math.copysign(5, 1))

    33print("clamp(50, 0, 100):", clamp(50, 0, 100))34print("clamp(150, 0, 100):", clamp(150, 0, 100))3536# Sign37print("\nSign (copysign):")38print("math.copysign(5, 1):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.copysign(5, 1))39print("math.copysign(5, -1):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.copysign(5, -1))40print("math.copysign(-5, 1):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.copysign(-5, 1))4142# Custom sign function43def sign(x):44    """Return sign of number (-1, 0, or 1)"""45    if x > 0:46        return 147    elif x < 0:48        return -149    else:50        return 05152print("\nSign function:")53print("sign(5):", sign(5))54print("sign(-5):", sign(-5))
    outputclamp(150, 0, 100): 100
    
    Sign (copysign):
    math.copysign(5, 1): 5.0
    math.copysign(5, -1): -5.0
    math.copysign(-5, 1): 5.0
    
    Sign function:
  6. def sign(x):

    pass 1 of 3
    42# Custom sign function43def sign(x5):44    """Return sign of number (-1, 0, or 1)"""45    if x > 0:
    All 3 passes — pass 1 is the card above
    passx
    15
    2-5
    30
  7. if x > 0:

    44"""Return sign of number (-1, 0, or 1)"""45if x5 > 0:46    return 147elif x < 0:
  8. print("sign(5):", sign(5))

    52print("\nSign function:")53print("sign(5):", sign(5))54print("sign(-5):", sign(-5))55print("sign(0):", sign(0))
    outputsign(5): 1
  9. elif x < 0:

    46    return 147elif x-5 < 0:48    return -149else:
  10. print("sign(-5):", sign(-5))

    53print("sign(5):", sign(5))54print("sign(-5):", sign(-5))55print("sign(0):", sign(0))
    outputsign(-5): -1
  11. a ← 3.14159, b ← 3.14, tolerance ← 0.01

    54print("sign(-5):", sign(-5))55print("sign(0):", sign(0))5657# Absolute difference58print("\nAbsolute difference:")59print("|5 - 10|:", abs(5 - 10))60print("|10 - 5|:", abs(10 - 5))61print("|-5 - (-10)|:", abs(-5 - (-10)))6263# Within tolerance64def within_tolerance(a, b, tol):65    """Check if values are within tolerance"""66    return abs(a - b) <= tol6768print("\nWithin tolerance:")69a→ 3.14159 = 3.1415970b→ 3.14 = 3.1471tolerance→ 0.01 = 0.0172print(f"{a3.14159} ≈ {b3.14} (±{tolerance0.01}): {within_tolerance(a, b, tolerance)}")
    outputsign(0): 0
    
    Absolute difference:
    |5 - 10|: 5
    |10 - 5|: 5
    |-5 - (-10)|: 5
    
    Within tolerance:
  12. def within_tolerance(a, b, tol):

    63# Within tolerance64def within_tolerance(a3.14159, b3.14, tol0.01):65    """Check if values are within tolerance"""66    return abs(a3.14159 - b3.14) <= tol0.01
  13. score ← 150

    71tolerance = 0.0172print(f"{a3.14159} ≈ {b3.14} (±{tolerance0.01}): {within_tolerance(a, b, tolerance)}")7374# Practical examples75print("\nPractical examples:")7677# Keep score in bounds78score→ 150 = 15079bounded = clamp(score150, 0, 100)80print(f"Score {score} bounded to [0,100]: {bounded}")
    output3.14159 ≈ 3.14 (±0.01): True
    
    Practical examples:
  14. bounded ← 100, volume ← 1.5

    78score = 15079bounded→ 100 = clamp(score150, 0, 100)80print(f"Score {score150} bounded to [0,100]: {bounded100}")8182# Volume control83volume→ 1.5 = 1.584valid_volume = clamp(volume1.5, 0.0, 1.0)85print(f"Volume {volume} clamped to [0,1]: {valid_volume}")
    outputScore 150 bounded to [0,100]: 100
  15. valid_volume ← 1.0, temp ← -5, min_temp ← 0, max_temp ← 30

    83volume = 1.584valid_volume→ 1.0 = clamp(volume1.5, 0.0, 1.0)85print(f"Volume {volume1.5} clamped to [0,1]: {valid_volume1.0}")8687# Temperature range88temp→ -5 = -589min_temp→ 0 = 090max_temp→ 30 = 3091valid_temp = clamp(temp-5, min_temp0, max_temp30)92print(f"Temp {temp}° bounded to [{min_temp},{max_temp}]: {valid_temp}")
    outputVolume 1.5 clamped to [0,1]: 1.0
  16. valid_temp ← 0, values ← [23, 45, 12, 67, 34], min_val ← 12, max_val ← 67

    90max_temp = 3091valid_temp→ 0 = clamp(temp-5, min_temp0, max_temp30)92print(f"Temp {temp-5}° bounded to [{min_temp0},{max_temp30}]: {valid_temp0}")9394# Find range95values→ [23, 45, 12, 67, 34] = [23, 45, 12, 67, 34]96min_val→ 12 = min(values[23, 45, 12, 67, 34])97max_val→ 67 = max(values[23, 45, 12, 67, 34])98range_val→ 55 = max_val67 - min_val1299print(f"\nValues: {values[23, 45, 12, 67, 34]}")100print(f"Range: {min_val12} to {max_val67} (span: {range_val55})")101102# Midpoint103def midpoint(a, b):104    """Calculate midpoint between two values"""105    return (a + b) / 2106107print("\nMidpoint:")108print("Between 10 and 20:", midpoint(10, 20))109print("Between -5 and 15:", midpoint(-5, 15))
    outputTemp -5° bounded to [0,30]: 0
    
    Values: [23, 45, 12, 67, 34]
    Range: 12 to 67 (span: 55)
    
    Midpoint:
  17. def midpoint(a, b):

    pass 1 of 2
    102# Midpoint103def midpoint(a10, b20):104    """Calculate midpoint between two values"""105    return (a10 + b20) / 2
  18. print("Between 10 and 20:", midpoint(10, 20))

    107print("\nMidpoint:")108print("Between 10 and 20:", midpoint(10, 20))109print("Between -5 and 15:", midpoint(-5, 15))
    outputBetween 10 and 20: 15.0
  19. def midpoint(a, b):

    pass 2 of 2
    102# Midpoint103def midpoint(a-5, b15):104    """Calculate midpoint between two values"""105    return (a-5 + b15) / 2
  20. values ← [5, 2, 9, 1, 7]

    108print("Between 10 and 20:", midpoint(10, 20))109print("Between -5 and 15:", midpoint(-5, 15))110111# Compare with tolerance112print("\nFloat comparison:")113print("0.1 + 0.2 == 0.3:", 0.1 + 0.2 == 0.3)114print("isclose(0.1 + 0.2, 0.3):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.isclose(0.1 + 0.2, 0.3))115116# Multiple comparisons117print("\nmath.isclose():")118print("isclose(1.0, 1.0001):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.isclose(1.0, 1.0001))119print("isclose(1.0, 1.0001, abs_tol=0.001):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.isclose(1.0, 1.0001, abs_tol=0.001))120print("isclose(1.0, 1.01, rel_tol=0.01):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.isclose(1.0, 1.01, rel_tol=0.01))121122# Find index of max/min123print("\nIndex of max/min:")124values→ [5, 2, 9, 1, 7] = [5, 2, 9, 1, 7]125print("Values:", values[5, 2, 9, 1, 7])126print("Index of max:", values[5, 2, 9, 1, 7].index(max(values)))127print("Index of min:", values[5, 2, 9, 1, 7].index(min(values)))
    outputBetween -5 and 15: 5.0
    
    Float comparison:
    0.1 + 0.2 == 0.3:
    isclose(0.1 + 0.2, 0.3): True
    
    math.isclose():
    isclose(1.0, 1.0001): False
    isclose(1.0, 1.0001, abs_tol=0.001): True
    isclose(1.0, 1.01, rel_tol=0.01): True
    
    Index of max/min:
    Values: [5, 2, 9, 1, 7]
    Index of max: 2
    Index of min: 3
isclose() Compares floats with tolerance to avoid precision errors - use instead of == for float comparisons.

Special Functions

Additional mathematical functions:

special.py
Replay: real traced execution (multi-file project)
# 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}")

  1. p1 ← (0, 0), p2 ← (3, 4), p3 ← (1, 2, 3), p4 ← (4, 6, 8), numbers ← [2, 3, 4]

    6# Hypotenuse7print("Hypotenuse:")8print("math.hypot(3, 4):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.hypot(3, 4))9print("math.hypot(5, 12):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.hypot(5, 12))10print("math.hypot(1, 1):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.hypot(1, 1))1112# Hypotenuse in N dimensions13print("\nHypotenuse (N dimensions):")14print("hypot(3, 4, 12):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.hypot(3, 4, 12))15print("hypot(1, 1, 1):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.hypot(1, 1, 1))1617# Expm1 (exp(x) - 1) - accurate for small x18print("\nExpm1 (e^x - 1):")19print("math.expm1(0):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.expm1(0))20print("math.expm1(1):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.expm1(1))21print("math.expm1(0.001):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.expm1(0.001))2223# Log1p (log(1 + x)) - accurate for small x24print("\nLog1p (ln(1 + x)):")25print("math.log1p(0):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.log1p(0))26print("math.log1p(1):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.log1p(1))27print("math.log1p(0.001):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.log1p(0.001))2829# Distance formula30print("\nDistance (math.dist):")31p1→ (0, 0) = (0, 0)32p2→ (3, 4) = (3, 4)33print(f"dist({p1(0, 0)}, {p2(3, 4)}):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.dist(p1, p2))3435p3→ (1, 2, 3) = (1, 2, 3)36p4→ (4, 6, 8) = (4, 6, 8)37print(f"dist({p3(1, 2, 3)}, {p4(4, 6, 8)}):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.dist(p3, p4))3839# Remainder40print("\nRemainder:")41print("math.remainder(10, 3):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.remainder(10, 3))42print("10 % 3:", 10 % 3)43print("math.remainder(10.5, 3):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.remainder(10.5, 3))4445# Modulo vs remainder46print("\nModulo vs Remainder:")47print("7 % 3:", 7 % 3)48print("remainder(7, 3):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.remainder(7, 3))49print("-7 % 3:", -7 % 3)50print("remainder(-7, 3):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.remainder(-7, 3))5152# FMod (modulo as in C)53print("\nfmod (C-style modulo):")54print("math.fmod(10, 3):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.fmod(10, 3))55print("math.fmod(-10, 3):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.fmod(-10, 3))5657# Prod (product of iterable) - Python 3.8+58print("\nProduct:")59numbers→ [2, 3, 4] = [2, 3, 4]60print(f"prod({numbers[2, 3, 4]}):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.prod(numbers))61print("prod([1, 2, 3, 4, 5]):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.prod([1, 2, 3, 4, 5]))6263# Sum with start value64print("\nSum:")65print("sum([1, 2, 3]):", sum([1, 2, 3]))66print("sum([1, 2, 3], 10):", sum([1, 2, 3], 10))6768# Fsum (accurate floating-point sum)69print("\nfsum (accurate sum):")70values→ [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1] = [0.1] * 1071print(f"sum({values[0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]}):", sum(values))72print(f"fsum({values[0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]}):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.fsum(values))7374# Special values75print("\nSpecial values:")76print("inf:", math.infinf)77print("-inf:", -math.infinf)78print("nan:", math.nannan)7980# Check special values81print("\nCheck special values:")82print("isinf(math.inf):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.isinf(math.infinf))83print("isnan(math.nan):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.isnan(math.nannan))84print("isfinite(100):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.isfinite(100))85print("isfinite(math.inf):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.isfinite(math.infinf))8687# NextAfter - Python 3.9+88print("\nNextAfter:")89try:
    outputHypotenuse:
    math.hypot(3, 4): 5.0
    math.hypot(5, 12): 13.0
    math.hypot(1, 1): 1.4142135623730951
    
    Hypotenuse (N dimensions):
    hypot(3, 4, 12): 13.0
    hypot(1, 1, 1): 1.7320508075688772
    
    Expm1 (e^x - 1):
    math.expm1(0): 0.0
    math.expm1(1): 1.718281828459045
    math.expm1(0.001): 0.0010005001667083417
    
    Log1p (ln(1 + x)):
    math.log1p(0): 0.0
    math.log1p(1): 0.6931471805599453
    math.log1p(0.001): 0.0009995003330835331
    
    Distance (math.dist):
    dist((0, 0), (3, 4)): 5.0
    dist((1, 2, 3), (4, 6, 8)): 7.0710678118654755
    
    Remainder:
    math.remainder(10, 3): 1.0
    10 % 3: 1
    math.remainder(10.5, 3): -1.5
    
    Modulo vs Remainder:
    7 % 3: 1
    remainder(7, 3): 1.0
    -7 % 3: 2
    remainder(-7, 3): -1.0
    
    fmod (C-style modulo):
    math.fmod(10, 3): 1.0
    math.fmod(-10, 3): -1.0
    
    Product:
    prod([2, 3, 4]): 24
    prod([1, 2, 3, 4, 5]): 120
    
    Sum:
    sum([1, 2, 3]): 6
    sum([1, 2, 3], 10): 16
    
    fsum (accurate sum):
    sum([0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]): 1.0
    fsum([0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]): 1.0
    
    Special values:
    inf: inf
    -inf: -inf
    nan: nan
    
    Check special values:
    isinf(math.inf): True
    isnan(math.nan): True
    isfinite(100): True
    isfinite(math.inf): False
    
    NextAfter:
  2. try:

    88print("\nNextAfter:")89try:90    print("nextafter(1.0, 2.0):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.nextafter(1.0, 2.0))91    print("nextafter(1.0, 0.0):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.nextafter(1.0, 0.0))92except AttributeError:
    outputnextafter(1.0, 2.0): 1.0000000000000002
    nextafter(1.0, 0.0): 0.9999999999999999
  3. print(" Ulp (unit in last place):")

    95# Ulp - Python 3.9+96print("\nUlp (unit in last place):")97try:
    output
    Ulp (unit in last place):
  4. try:

    96print("\nUlp (unit in last place):")97try:98    print("ulp(1.0):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.ulp(1.0))99    print("ulp(10.0):", math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.ulp(10.0))100except AttributeError:
    outputulp(1.0): 2.220446049250313e-16
    ulp(10.0): 1.7763568394002505e-15
  5. a ← 1e+100, b ← 1e+100, hypot ← 1.414213562373095e+100, small ← 0.0001

    103# Practical examples104print("\nPractical examples:")105106# Calculate hypotenuse without overflow107a→ 1e+100 = 1e100108b→ 1e+100 = 1e100109hypot→ 1.414213562373095e+100 = math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.hypot(a1e+100, b1e+100)110print(f"Hypotenuse of very large sides: {hypot1.414213562373095e+100}")111112# Accurate small calculations113small→ 0.0001 = 0.0001114exp_result→ 0.00010000500016667084 = math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.expm1(small0.0001)115log_result→ 9.999500033330834e-05 = math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.log1p(small0.0001)116print(f"expm1({small0.0001}): {exp_result0.00010000500016667084}")117print(f"log1p({small0.0001}): {log_result9.999500033330834e-05}")118119# Accurate sum120values→ [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1] = [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]121regular_sum→ 1.0 = sum(values[0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1])122accurate_sum→ 1.0 = math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.fsum(values[0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1])123print(f"Regular sum: {regular_sum1.0}")124print(f"Accurate sum: {accurate_sum1.0}")125print(f"Expected: 1.0")126127# Product calculation128discount_factors→ [0.9, 0.95, 0.98] = [0.9, 0.95, 0.98]129final_multiplier→ 0.8379 = math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.prod(discount_factors[0.9, 0.95, 0.98])130price→ 100 = 100131final_price→ 83.78999999999999 = price100 * final_multiplier0.8379132print(f"\nSequential discounts: {discount_factors[0.9, 0.95, 0.98]}")133print(f"Final multiplier: {final_multiplier0.8379:.4f}")134print(f"Price ${price100} -> ${final_price83.78999999999999:.2f}")
    output
    Practical examples:
    Hypotenuse of very large sides: 1.414213562373095e+100
    expm1(0.0001): 0.00010000500016667084
    log1p(0.0001): 9.999500033330834e-05
    Regular sum: 1.0
    Accurate sum: 1.0
    Expected: 1.0
    
    Sequential discounts: [0.9, 0.95, 0.98]
    Final multiplier: 0.8379
    Price $100 -> $83.79

Exercise: practical.py

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