w3resource

NumPy: Calculate 2p for all elements in a given array


33. Compute 2^p Element-wise

Write a NumPy program to calculate 2p for all elements in a given array.

Sample Solution:

Python Code:

# Importing the NumPy library
import numpy as np

# Creating an array of float32 type
x = np.array([1., 2., 3., 4.], np.float32)

# Displaying the original array
print("Original array: ")
print(x)

# Calculating exp(x) - 1 for each element of the array x
print("\nexp(x)-1 for all elements of the said array:")
r1 = np.expm1(x)
r2 = np.exp(x) - 1.

# Asserting whether the results from np.expm1 and np.exp - 1 are close
assert np.allclose(r1, r2)

# Printing the resulting array after exp(x) - 1 calculation
print(r1) 

Sample Output:

Original array: 
[1. 2. 3. 4.]

exp(x)-1 for all elements of the said array:
[ 1.7182819  6.389056  19.085537  53.59815  ]

Explanation:

In the above code –

x = np.array([1., 2., 3., 4.], np.float32): This line creates a one-dimensional NumPy array x of data type float32 is created with the values [1., 2., 3., 4.].

r1 = np.exp2(x): Here the np.exp2() function is called with the x array as the input. This calculates the exponential value of 2 raised to the power of each element in the input array. The result of np.exp2() is assigned to r1.

r2 = 2 ** x: This code approaches another way of raising 2 to the power of each element of the array x is to use the exponentiation operator ** with the base 2 and the x array.

assert np.allclose(r1, r2): Finally, the np.allclose() function is used to check if r1 and r2 are equal within a certain tolerance. The result shows that the values computed by np.exp2 and 2 ** x are the same for all elements within a certain tolerance.

For more Practice: Solve these Related Problems:

  • Implement a function that raises 2 to the power of each element in an array using np.power.
  • Test the function on an array of exponents, including negative and fractional values, to verify output accuracy.
  • Create a solution that utilizes broadcasting to compute 2^p when the exponent is given as a scalar.
  • Compare the result with manual computation using logarithms and exponentiation for validation.

Go to:


PREV : Compute exp(x) - 1
NEXT : Compute Logarithms (Natural, Base 10, Base 2)

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.