NumPy float_power()

The numpy.float_power() function raises each base in x1 to the positionally corresponding power in x2, element-wise. Unlike the regular power() function, it ensures a minimum floating-point precision of float64 for accurate results, even when using lower-precision data types.

Syntax

</>
Copy
numpy.float_power(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True)

Parameters

ParameterTypeDescription
x1array_likeBase values to be raised to the power.
x2array_likeExponent values. Must be broadcastable with x1.
outndarray, None, or tuple of ndarray and None, optionalOptional output array where the result is stored. If None, a new array is created.
wherearray_like, optionalBoolean mask specifying which elements to compute. Elements where where=False retain their original value.
castingstr, optionalDefines the casting behavior when computing the function.
orderstr, optionalMemory layout order of the output array.
dtypedata-type, optionalDefines the data type of the output array.
subokbool, optionalDetermines if subclasses of ndarray are preserved in the output.

Return Value

Returns an array where each element is the base from x1 raised to the exponent in x2. If both x1 and x2 are scalars, a scalar is returned.


Examples

1. Computing Power of Single Values

Here, we compute 2.5 raised to the power of 3.

</>
Copy
import numpy as np

# Define base and exponent values
base = 2.5
exponent = 3

# Compute power
result = np.float_power(base, exponent)

# Print the result
print("2.5^3 =", result)

Output:

2.5^3 = 15.625

2. Computing Power for Arrays

We compute the power for an array of bases and an array of exponents.

</>
Copy
import numpy as np

# Define base and exponent arrays
bases = np.array([1, 2, 3, 4, 5])
exponents = np.array([2, 3, 4, 5, 6])

# Compute power
result = np.float_power(bases, exponents)

# Print the results
print("Bases:", bases)
print("Exponents:", exponents)
print("Result:", result)

Output:

Bases: [1 2 3 4 5]
Exponents: [2 3 4 5 6]
Result: [   1.    8.   81. 1024. 15625.]

3. Using the out Parameter

Using an output array to store results instead of creating a new array.

</>
Copy
import numpy as np

# Define base and exponent arrays
bases = np.array([2, 3, 4])
exponents = np.array([3, 2, 1])

# Create an output array with the same shape
output_array = np.empty_like(bases, dtype=np.float64)

# Compute power and store the result in output_array
np.float_power(bases, exponents, out=output_array)

# Print the results
print("Computed power values:", output_array)

Output:

Computed power values: [8. 9. 4.]