YouTip LogoYouTip

Ref Math Log

## Python math.log() Method The `math.log()` method is a built-in function in Python's standard `math` module. By default, it calculates the natural logarithm (logarithm to the base $e$) of a given number. It can also calculate the logarithm of a number to any specified base. --- ### Syntax To use the `math.log()` method, you must first import the `math` module: ```python import math math.log(x[, base]) ``` #### Parameters * **`x`** (Required): A numeric value (integer or float). It must be greater than 0. * If `x` is not a number, a `TypeError` is raised. * If `x` is zero or a negative number, a `ValueError` is raised. * **`base`** (Optional): The logarithmic base to use for the calculation. * If omitted, it defaults to $e$ (Euler's number, approximately `2.71828`), calculating the natural logarithm. #### Return Value * Returns a **float** representing the logarithm of `x` to the given `base`. --- ### Code Examples #### Example 1: Calculating the Natural Logarithm (Base $e$) When you omit the `base` argument, `math.log()` calculates the natural logarithm ($\ln(x)$). ```python import math # Calculate the natural logarithm of e (approx. 2.7183) print(math.log(2.718281828459045)) # Calculate the natural logarithm of 2 print(math.log(2)) # Calculate the natural logarithm of 1 print(math.log(1)) ``` **Output:** ```text 1.0 0.6931471805599453 0.0 ``` --- #### Example 2: Calculating Logarithms with a Custom Base You can specify a custom base (such as base 10 or base 2) as the second argument. ```python import math # Calculate the logarithm of 100 to base 10 print(math.log(100, 10)) # Calculate the logarithm of 8 to base 2 print(math.log(8, 2)) # Calculate the logarithm of 9 to base 3 print(math.log(9, 3)) ``` **Output:** ```text 2.0 3.0 2.0 ``` --- ### Considerations & Exceptions #### 1. Value Error (Non-positive numbers) Logarithms are only defined for strictly positive numbers ($x > 0$). Passing `0` or a negative number will result in a `ValueError`. ```python import math try: math.log(0) except ValueError as e: print(f"ValueError: {e}") try: math.log(-5) except ValueError as e: print(f"ValueError: {e}") ``` **Output:** ```text ValueError: math domain error ValueError: math domain error ``` #### 2. Type Error (Non-numeric input) Passing a string or any other non-numeric type will raise a `TypeError`. ```python import math try: math.log("ten") except TypeError as e: print(f"TypeError: {e}") ``` **Output:** ```text TypeError: must be real number, not str ``` #### 3. Specialized Logarithmic Functions For better precision and performance, Python's `math` module provides specialized functions for common bases: * `math.log10(x)`: More accurate than `math.log(x, 10)` for base-10 calculations. * `math.log2(x)`: More accurate than `math.log(x, 2)` for base-2 calculations. * `math.log1p(x)`: Calculates $\ln(1 + x)$ accurately for values of $x$ close to zero.
← Ref Math Log10Ref Math Ceil β†’