2

I know np.exp2(x) exists that calculates 2^x where x is a numpy array, however, I am looking for a method that does K^x where K is any arbitrary number. Is there any elegant way of doing it rather than stretching out K to the shape of x and doing a piecewise exponent?

1
  • @tel: The "piecewise" seems to make things more confusing rather than less. Commented Nov 22, 2018 at 8:24

2 Answers 2

2

Just use the standard Python exponentiation operator **:

K**x

For example, if you have:

x = np.array([1,2,3])
K = 3

print(K**x)

The output is:

[ 3  9 27]

Notes

For Python classes, the behavior of the binary ** operator is implemented via the __pow__, __rpow__, and __ipow__ magic methods (the reality for np.ndarray is slightly more complicated since it's implemented in the C layer, but that's not actually important here). For Numpy arrays, these magic methods in turn appear to call numpy.power, so you can expect that ** will have the same behavior as documented for numpy.power. In particular,

Note that an integer type raised to a negative integer power will raise a ValueError.

Sign up to request clarification or add additional context in comments.

2 Comments

small note: cast K to a float or else negative numbers in the array will throw an error.
@Vj- I added a note about the implementation of **, including where it mentions that particular error in the documentation
2

With numpy you can just use numpy.power

arr = numpy.array([1,2,3])
print(numpy.power(3,arr)) # Outputs [ 3  9 27]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.