Compute the natural logarithm, with an optional base.
What You Will Learn
log(value) uses the natural base e; log(value, base) uses a change of base. Inputs must be positive and the base positive and not one.
For floating-point results, remember that stored values are approximations. Rounding a displayed value does not change the exact value used by later calculations.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
import math
print(math.log(math.e))
How the Example Works
- The imports provide the standard-library tools used in the demonstration: math.
- The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.
For the chosen input, the expression math.log(math.e) prints 1.0. Compare that result with the rule above before you change the argument.
Expected output from the example:
1.0
Another Example: Compare the Results
Try a second input and compare it with the first. Notice whether the result changes in type, value, order, or number of items.
import math
print(math.log(100, 10), math.log(math.e))
Expected output:
2.0 1.0
When You Would Use This
This operation can support measurements, numeric reports, simulations, or input validation. Choose integer operations when exact integer answers are required, and check floating-point rounding when displaying measured values. Validate units and input domains before using the result in a calculation.
Practice: Modify the Code
Calculate a logarithm in base five.
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Taking a logarithm of zero or a negative real value.
- Overlooking this documented constraint: inputs must be positive and the base positive and not one.
Key Takeaways
- Compute the natural logarithm, with an optional base.
- log(value) uses the natural base e; log(value, base) uses a change of base.
- Apply this operation only after checking the assumptions and input conditions shown in the example.