Kahibaro
Discord Login Register

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.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:

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

Common angles:

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

Converting Between Degrees and Radians

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

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:

Always remember to start with:

import math

before using these functions.

Views: 16

Comments

Please login to add a comment.

Don't have an account? Register now!