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 input value is raised with scimath in Python
The numpy.emath.power() function computes x raised to the power p (x**p) and handles negative values by converting results to the complex domain when necessary. This is particularly useful for mathematical operations that may produce complex results.
Syntax
numpy.emath.power(x, p)
Parameters
The function accepts the following parameters ?
- x ? The base value(s). Can be a scalar or array-like.
- p ? The exponent(s). Can be a scalar or array-like with the same shape as x.
Basic Example with Positive Values
Let's start with a simple example using positive integers ?
import numpy as np
# Creating a numpy array
arr = np.array([2, 4, 8, 16, 32])
print("Original Array:", arr)
# Raise each element to the power of 2
result = np.emath.power(arr, 2)
print("Result (power of 2):", result)
Original Array: [ 2 4 8 16 32] Result (power of 2): [ 4 16 64 256 1024]
Handling Negative Values
The key advantage of emath.power() is its ability to handle negative values by converting to complex domain ?
import numpy as np
# Array with negative values
arr = np.array([-4, -2, 0, 2, 4])
print("Array with negatives:", arr)
# Raise to fractional power (would produce complex results for negatives)
result = np.emath.power(arr, 0.5)
print("Square root (including complex):", result)
Array with negatives: [-4 -2 0 2 4] Square root (including complex): [0.+2.j 0.+1.41421356j 0.+0.j 1.41421356+0.j 2.+0.j]
Different Power Values
You can use arrays for both base and exponent values ?
import numpy as np
# Different bases and powers
bases = np.array([2, 3, 4, 5])
powers = np.array([2, 3, 0.5, -1])
result = np.emath.power(bases, powers)
print("Bases:", bases)
print("Powers:", powers)
print("Results:", result)
Bases: [2 3 4 5] Powers: [ 2. 3. 0.5 -1. ] Results: [4. 27. 2. 0.2]
Comparison with Standard Power
| Function | Negative Base | Result Type | Error Handling |
|---|---|---|---|
np.power() |
May raise warnings/errors | Real (when possible) | Warnings for invalid operations |
np.emath.power() |
Converts to complex | Complex (when needed) | Automatic complex conversion |
Conclusion
Use numpy.emath.power() when working with potentially negative values that need fractional exponents. It automatically handles complex number conversion, making it safer for mathematical operations that might produce complex results.
