Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to catch FloatingPointError Exception in Python?
A FloatingPointError in Python is an exception that occurs when there is an error in floating-point calculations. By default, Python does not raise this error for operations like dividing by zero; instead, it returns inf or nan. To catch this error, you need to enable it explicitly using NumPy.
When Does FloatingPointError Occur?
FloatingPointError can occur in cases like:
- Divide by zero in floating-point calculations (if enabled)
- Overflow in floating-point operations
- Invalid operations resulting in nan values
- Underflow when numbers become too small to represent
Enabling FloatingPointError in NumPy
To raise FloatingPointError, you need to configure NumPy's error handling using the seterr() method. This method allows you to specify how different types of floating-point errors should be handled.
Syntax
numpy.seterr(all=None, divide=None, over=None, under=None, invalid=None)
Parameters include 'ignore', 'warn', 'raise', and 'call'.
Catching Division by Zero
Here's how to enable and catch division by zero errors ?
import numpy as np
# Enable FloatingPointError for division by zero
np.seterr(divide='raise')
try:
a = np.array([1.0])
b = np.array([0.0])
result = a / b
except FloatingPointError as e:
print("Division error caught:", e)
Division error caught: divide by zero encountered in divide
Catching Overflow Errors
When calculations exceed the maximum representable value, an overflow occurs. NumPy can represent values up to approximately 1.79e+308 ?
import numpy as np
# Enable overflow error handling
np.seterr(over='raise')
try:
result = np.exp(1000) # e^1000 causes overflow
print("Result:", result)
except FloatingPointError as e:
print("Overflow error caught:", e)
Overflow error caught: overflow encountered in exp
Catching Invalid Operations
Invalid operations like square root of negative numbers can also raise FloatingPointError ?
import numpy as np
# Enable invalid operation error handling
np.seterr(invalid='raise')
try:
result = np.sqrt(-1) # Invalid: square root of negative number
print("Result:", result)
except FloatingPointError as e:
print("Invalid operation caught:", e)
Invalid operation caught: invalid value encountered in sqrt
Enabling All FloatingPoint Errors
You can enable all floating-point errors at once using all='raise' ?
import numpy as np
# Enable all floating-point errors
np.seterr(all='raise')
operations = [
("Division by zero", lambda: np.array([1.0]) / np.array([0.0])),
("Invalid sqrt", lambda: np.sqrt(-1)),
("Overflow", lambda: np.exp(1000))
]
for desc, operation in operations:
try:
result = operation()
print(f"{desc}: {result}")
except FloatingPointError as e:
print(f"{desc} caught: {e}")
Division by zero caught: divide by zero encountered in divide Invalid sqrt caught: invalid value encountered in sqrt Overflow caught: overflow encountered in exp
Comparison of Error Handling Options
| Option | Behavior | Use Case |
|---|---|---|
'ignore' |
No action taken | Default behavior |
'warn' |
Print warning message | Debugging purposes |
'raise' |
Raise FloatingPointError | Strict error handling |
'call' |
Call custom function | Custom error handling |
Conclusion
Use NumPy's seterr() to enable FloatingPointError exceptions for strict floating-point error handling. Combine with try-except blocks to gracefully handle division by zero, overflow, and invalid operations in your calculations.
