Calculate log(1 + value) accurately when value is close to zero.
What You Will Learn
log1p() avoids losing precision from forming 1 + a tiny floating-point value before taking the logarithm.
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.log1p(1e-12))
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.log1p(1e-12) prints 9.999999999995e-13. Compare that result with the rule above before you change the argument.
Expected output from the example:
9.999999999995e-13
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.log1p(0.000001), math.log(1.000001))
Expected output:
9.999995000003334e-07 9.999994999180668e-07
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
Compare log1p(1e-12) with log(1+1e-12).
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
- Calling log(1+x) for tiny x and assuming identical numerical accuracy.
- Skipping invalid or boundary inputs when adapting a numeric function to real user data.
Key Takeaways
- Calculate log(1 + value) accurately when value is close to zero.
- log1p() avoids losing precision from forming 1 + a tiny floating-point value before taking the logarithm.
- Apply this operation only after checking the assumptions and input conditions shown in the example.