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
Return the result of the power to which the negative input value is raised with scimath in Python
To return the result of the power to which the input value is raised with scimath, use the numpy.emath.power() method in Python. This function computes x to the power p (x**p) and automatically converts negative values to the complex domain when necessary.
The numpy.emath.power() function handles negative bases gracefully by returning complex numbers, unlike the regular numpy.power() which may produce warnings or errors with negative values.
Syntax
numpy.emath.power(x, p)
Parameters
x − The base value(s). Can be a scalar or array containing negative values.
p − The exponent(s). If x contains multiple values, p must be a scalar or contain the same number of values as x.
Return Value
Returns x raised to the power p. For negative bases, the result is automatically converted to complex numbers.
Example with Negative Values
import numpy as np
# Create array with negative values
arr = np.array([2, -4, -8, 16, -32])
print("Our Array:")
print(arr)
print("\nArray dimensions:", arr.ndim)
print("Array datatype:", arr.dtype)
print("Array shape:", arr.shape)
# Use emath.power() to handle negative values
result = np.emath.power(arr, 2)
print("\nResult of arr^2:")
print(result)
Our Array: [ 2 -4 -8 16 -32] Array dimensions: 1 Array datatype: int64 Array shape: (5,) Result of arr^2: [ 4.+0.j 16.+0.j 64.+0.j 256.+0.j 1024.+0.j]
Example with Different Exponents
import numpy as np
# Different exponents for each element
bases = np.array([-2, 3, -4, 5])
exponents = np.array([3, 2, 0.5, -1])
result = np.emath.power(bases, exponents)
print("Bases:", bases)
print("Exponents:", exponents)
print("Results:", result)
Bases: [-2 3 -4 5] Exponents: [ 3. 2. 0.5 -1. ] Results: [-8. +0.j 9. +0.j 0. +2.j 0.2 +0.j ]
Comparison with Regular Power
| Function | Handles Negative Bases | Return Type | Best For |
|---|---|---|---|
numpy.power() |
May warn/error | Real numbers | Positive bases only |
numpy.emath.power() |
Yes (complex result) | Complex numbers | Mixed positive/negative bases |
Conclusion
Use numpy.emath.power() when working with arrays that may contain negative values. It automatically handles complex number conversion and prevents mathematical errors that can occur with negative bases and fractional exponents.
