KAHIBARO Bookshelves
Discord Login Register

12.3.1. math

Working with the `math` Module

The math module is a standard Python library that gives you many useful mathematical functions and constants that are not built into basic Python.

To use it, you must import it at the top of your file (or before you call its functions):

import math

After importing, you access its tools with math.something, like math.sqrt(16).

Math Constants: `math.pi` and `math.e`

The math module provides some important mathematical constants.

`math.pi`

math.pi is the value of $\pi$ (pi), approximately $3.14159\ldots$

import math
print(math.pi)        # 3.141592653589793
circumference = 2 * math.pi * 5   # circle with radius 5
print(circumference)

Use math.pi when working with circles, angles (in radians), and trigonometry.

`math.e`

math.e is the base of the natural logarithm, $e \approx 2.71828\ldots$

import math
print(math.e)         # 2.718281828459045

You’ll mostly see math.e in more advanced math (growth/decay, logarithms, etc.), but it’s useful to know it exists.

Square Roots and Powers

Python already has the ** operator for powers, but the math module adds more precise and sometimes faster tools.

`math.sqrt(x)` — Square Root

Returns the square root of a non‑negative number $x$.

import math
print(math.sqrt(16))   # 4.0
print(math.sqrt(2))    # 1.4142135623730951

Note:

  • math.sqrt(x) only works for $x \ge 0$. For negative numbers, it raises a ValueError.

`math.pow(x, y)` — Power (as floats)

Raises $x$ to the power $y$, always returning a float.

import math
print(math.pow(2, 3))   # 8.0
print(2 ** 3)           # 8

For most everyday use, ** is perfectly fine. math.pow is just another option and always returns a float.

Rounding and Related Functions

Python has a built‑in round(), but the math module provides more specific rounding behaviors.

`math.floor(x)` — Round Down

Returns the largest integer less than or equal to $x$ (always rounds down).

$$\text{floor}(3.9) = 3,\quad \text{floor}(-1.2) = -2$$

import math
print(math.floor(3.9))     # 3
print(math.floor(2.0))     # 2
print(math.floor(-1.2))    # -2

`math.ceil(x)` — Round Up

Returns the smallest integer greater than or equal to $x$ (always rounds up).

$$\text{ceil}(3.1) = 4,\quad \text{ceil}(-1.2) = -1$$

import math
print(math.ceil(3.1))      # 4
print(math.ceil(2.0))      # 2
print(math.ceil(-1.2))     # -1

`math.trunc(x)` — Cut Off Decimals

Removes the decimal part and keeps only the integer part (toward zero).

import math
print(math.trunc(3.9))     # 3
print(math.trunc(-3.9))    # -3

In summary:

  • floor: always down
  • ceil: always up
  • trunc: toward zero (just cut off the decimal part)

Absolute Value and Sign

`math.fabs(x)` — Floating Absolute Value

Returns the absolute value as a float:

import math
print(math.fabs(-5))     # 5.0
print(abs(-5))           # 5 (built-in)

abs() is built‑in and often enough; math.fabs() always returns a float.

Trigonometry: `sin`, `cos`, `tan`

The math module includes many trigonometric functions. They use radians, not degrees.

Radians vs Degrees

  • Degrees: 0° to 360°
  • Radians: 0 to $2\pi$

Common angles:

  • $0^\circ = 0$ radians
  • $90^\circ = \frac{\pi}{2}$ radians
  • $180^\circ = \pi$ radians
  • $360^\circ = 2\pi$ radians

You usually do not type radians by hand; you can use conversion functions.

Converting Between Degrees and Radians

  • math.radians(deg) — degrees $\to$ radians
  • math.degrees(rad) — radians $\to$ degrees
import math
print(math.radians(180))     # 3.141592653589793 (pi)
print(math.degrees(math.pi)) # 180.0

`math.sin(x)`, `math.cos(x)`, `math.tan(x)`

These compute sine, cosine, and tangent of an angle in radians.

import math
# 90 degrees in radians
angle = math.radians(90)
print(math.sin(angle))   # 1.0 (approximately)
print(math.cos(angle))   # 0.0 (approximately)
print(math.tan(angle))   # very large number (undefined in exact math)

Typical use: working with angles, waves, circles, or simple physics.

Inverse Trigonometric Functions

  • math.asin(x)
  • math.acos(x)
  • math.atan(x)

These do the opposite: they take a ratio and return an angle (in radians).

import math
angle = math.asin(1)      # sin(angle) = 1
print(angle)              # 1.5707963267948966 (about pi/2)
print(math.degrees(angle))# 90.0

Logarithms and Exponentials

You may not use these much at the very beginning, but they appear often in more advanced topics.

Natural Logarithm: `math.log(x)`

By default, math.log(x) computes the natural logarithm (base $e$).

It answers the question: “To what power must I raise $e$ to get $x$?”

import math
print(math.log(math.e))   # 1.0
print(math.log(1))        # 0.0

You can also specify another base:

import math
print(math.log(8, 2))     # 3.0, because 2^3 = 8

Base-10 Logarithm: `math.log10(x)`

Logarithm with base $10$:

import math
print(math.log10(1000))   # 3.0, because 10^3 = 1000

Exponential: `math.exp(x)`

Computes $e^x$:

import math
print(math.exp(1))      # about 2.718281828 (e)
print(math.exp(2))      # about 7.3890560989

Minimum, Maximum, and Other Helpers

Python has built‑in min() and max(), but math offers a few numeric helpers.

`math.fsum(iterable)` — Precise Sum

Adds a sequence of numbers more accurately than the built‑in sum(), especially for floats.

import math
numbers = [0.1] * 10
print(sum(numbers))      # may not be exactly 1.0
print(math.fsum(numbers))# more precise 1.0

`math.isfinite(x)`, `math.isinf(x)`, `math.isnan(x)`

These check special numeric values like “infinity” and “NaN” (Not a Number).

import math
print(math.isfinite(10))        # True
print(math.isinf(float('inf'))) # True
print(math.isnan(float('nan'))) # True

You won’t need these early on, but they are useful when dealing with complex numeric calculations.

Practical Examples Using `math`

Example 1: Area of a Circle

Area of a circle with radius $r$ is:

$$A = \pi r^2$$

import math
radius = 5
area = math.pi * (radius ** 2)
print("Area:", area)

Example 2: Distance Between Two Points

Distance between points $(x_1, y_1)$ and $(x_2, y_2)$:

$$
d = \sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2}
$$

import math
x1, y1 = 0, 0
x2, y2 = 3, 4
dx = x2 - x1
dy = y2 - y1
distance = math.sqrt(dx**2 + dy**2)
print("Distance:", distance)   # 5.0

Example 3: Angle of a Slope

You have a ramp that rises 1 meter over 4 meters of length. The angle $\theta$ in degrees:

  1. Use atan to get the angle in radians.
  2. Convert to degrees.
import math
rise = 1
run = 4
theta_rad = math.atan(rise / run)
theta_deg = math.degrees(theta_rad)
print("Angle in degrees:", theta_deg)

When to Use `math`

Use the math module when you need:

  • Precise mathematical constants (math.pi, math.e)
  • Square roots and advanced powers (math.sqrt, math.pow)
  • More control over rounding (math.floor, math.ceil, math.trunc)
  • Trigonometric functions (math.sin, math.cos, math.tan)
  • Logarithms and exponentials (math.log, math.log10, math.exp)
  • More accurate floating‑point sums (math.fsum)

Always remember to start with:

import math

before using these functions.

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Chapter 1: What Is Programming?
    • ☰ 1.1. What is a computer program?
      • ☰ 1.2. What is Python?
        • ☰ 1.3. Where is Python used?
          • ☰ 1.4. How programming helps solve problems
            • ☰ 1.5. Your first Python program
            • ☰ 2. Chapter 2: Setting Up Python
              • ☰ 2.1. Installing Python (Windows / macOS / Linux)
                • ☰ 2.2. Using Python in the terminal
                  • ☰ 2.3. Using an IDE (IDLE / VS Code)
                    • ☰ 2.4. Running Python scripts
                      • ☰ 2.5. Python interactive mode
                      • ☰ 3. Chapter 3: Variables and Data Types
                        • ☰ 3.1. What is a variable?
                          • ☰ 3.2. Creating variables
                            • ☰ 3.3. Numbers
                              • ☰ 3.4. Test
                                • ☰ 3.5. Boolean values
                                  • ☰ 3.6. Type checking
                                  • ☰ 4. Chapter 4: Basic Operations
                                    • ☰ 4.1. Arithmetic operations
                                      • ☰ 4.2. Working with numbers
                                        • ☰ 4.3. String operations
                                          • ☰ 4.4. Combining text and variables
                                            • ☰ 4.5. Comments in Python
                                            • ☰ 5. Chapter 5: User Input and Output
                                              • ☰ 5.1. Getting input from the user
                                                • ☰ 5.2. Converting input to numbers
                                                  • ☰ 5.3. Formatting output
                                                    • ☰ 5.4. Writing interactive programs
                                                    • ☰ 6. Chapter 6: Conditions
                                                      • ☰ 6.1. Comparison operators
                                                        • ☰ 6.2. Logical operators
                                                          • ☰ 6.3. if, elif, else
                                                            • ☰ 6.4. Nested conditions
                                                              • ☰ 6.5. Common beginner mistakes
                                                              • ☰ 7. Chapter 7: Loops
                                                                • ☰ 7.1. Why loops are useful
                                                                  • ☰ 7.2. for loops
                                                                    • ☰ 7.3. while loops
                                                                      • ☰ 7.4. Loop counters
                                                                        • ☰ 7.5. break and continue
                                                                          • ☰ 7.6. Loop exercises
                                                                          • ☰ 8. Chapter 8: Data Collections
                                                                            • ☰ 8.1. Lists
                                                                              • ☰ 8.2. Tuples
                                                                                • ☰ 8.3. Dictionaries
                                                                                  • ☰ 8.4. Sets (basics)
                                                                                    • ☰ 8.5. Choosing the right data structure
                                                                                    • ☰ 9. Chapter 9: Functions
                                                                                      • ☰ 9.1. Why functions matter
                                                                                        • ☰ 9.2. Defining functions
                                                                                          • ☰ 9.3. Parameters and arguments
                                                                                            • ☰ 9.4. Return values
                                                                                              • ☰ 9.5. Scope (local vs global)
                                                                                                • ☰ 9.6. Reusing code
                                                                                                • ☰ 10. Chapter 10: Working with Files
                                                                                                  • ☰ 10.1. What is a file?
                                                                                                    • ☰ 10.2. Reading text files
                                                                                                      • ☰ 10.3. Writing and appending files
                                                                                                        • ☰ 10.4. File paths
                                                                                                          • ☰ 10.5. Simple file-based programs
                                                                                                          • ☰ 11. Chapter 11: Errors and Debugging
                                                                                                            • ☰ 11.1. Types of errors
                                                                                                              • ☰ 11.2. Reading error messages
                                                                                                                • ☰ 11.3. Common beginner errors
                                                                                                                  • ☰ 11.4. try and except
                                                                                                                    • ☰ 11.5. Debugging strategies
                                                                                                                    • ☰ 12. Chapter 12: Using Python Libraries
                                                                                                                      • ☰ 12.1. What is a library?
                                                                                                                        • ☰ 12.2. Importing modules
                                                                                                                          • ☰ 12.3. Standard libraries
                                                                                                                            • ☰ 12.3.1. math
                                                                                                                              • ☰ 12.3.2. random
                                                                                                                                • ☰ 12.3.3. datetime
                                                                                                                                • ☰ 12.4. Installing external libraries with pip
                                                                                                                                • ☰ 13. Chapter 13: Object-Oriented Programming
                                                                                                                                  • ☰ 13.1. What is object-oriented programming?
                                                                                                                                    • ☰ 13.2. Classes and objects
                                                                                                                                      • ☰ 13.3. The `__init__` method
                                                                                                                                        • ☰ 13.4. Attributes and methods
                                                                                                                                          • ☰ 13.5. Encapsulation
                                                                                                                                            • ☰ 13.6. Inheritance (basics)
                                                                                                                                              • ☰ 13.7. Simple OOP examples
                                                                                                                                              • ☰ 14. Chapter 14: Automation with Python
                                                                                                                                                • ☰ 14.1. What is automation?
                                                                                                                                                  • ☰ 14.2. Automating simple tasks
                                                                                                                                                    • ☰ 14.3. Working with files and folders
                                                                                                                                                      • ☰ 14.4. Automating text processing
                                                                                                                                                        • ☰ 14.5. Scheduling scripts
                                                                                                                                                          • ☰ 14.6. Practical automation examples
                                                                                                                                                          • ☰ 15. Chapter 15: Web Development with Python
                                                                                                                                                            • ☰ 15.1. How the web works (basic overview)
                                                                                                                                                              • ☰ 15.2. Introduction to Flask
                                                                                                                                                                • ☰ 15.3. Creating a simple web server
                                                                                                                                                                  • ☰ 15.4. Routing and templates
                                                                                                                                                                    • ☰ 15.5. Handling user input (forms)
                                                                                                                                                                      • ☰ 15.6. Very basic APIs
                                                                                                                                                                      • ☰ 16. Chapter 16: Data Science with Python
                                                                                                                                                                        • ☰ 16.1. What is data science?
                                                                                                                                                                          • ☰ 16.2. Working with data
                                                                                                                                                                            • ☰ 16.3. Introduction to NumPy
                                                                                                                                                                              • ☰ 16.4. Introduction to pandas
                                                                                                                                                                                • ☰ 16.5. Data visualization with matplotlib
                                                                                                                                                                                  • ☰ 16.6. Simple data analysis examples
                                                                                                                                                                                  • ☰ 17. Chapter 17: Mini Projects
                                                                                                                                                                                    • ☰ 17.1. Number guessing game
                                                                                                                                                                                      • ☰ 17.2. Simple calculator
                                                                                                                                                                                        • ☰ 17.3. To-do list
                                                                                                                                                                                          • ☰ 17.4. Password generator
                                                                                                                                                                                            • ☰ 17.5. Quiz application
                                                                                                                                                                                              • ☰ 17.6. Small web or data project
                                                                                                                                                                                              • ☰ 18. Chapter 18: Next Steps
                                                                                                                                                                                                • ☰ 18.1. How to practice Python
                                                                                                                                                                                                  • ☰ 18.2. Writing clean and readable code
                                                                                                                                                                                                    • ☰ 18.3. Choosing a specialization
                                                                                                                                                                                                      • ☰ 18.3.1. Web development
                                                                                                                                                                                                        • ☰ 18.3.2. Data science
                                                                                                                                                                                                          • ☰ 18.3.3. Automation
                                                                                                                                                                                                            • ☰ 18.3.4. Software development
                                                                                                                                                                                                            • ☰ 18.4. Learning resources and communities
                                                                                                                                                                                                            • ☰ 19. Appendix
                                                                                                                                                                                                              • ☰ 19.1. Python syntax cheat sheet
                                                                                                                                                                                                                • ☰ 19.2. Common errors and solutions
                                                                                                                                                                                                                  • ☰ 19.3. Glossary of terms