Advanced NumPy Exercises - Calculate the exponential of each element in a 5x5 array
NumPy: Advanced Exercise-15 with Solution
Write a NumPy program to create a 5x5 array with random values and calculate the exponential of each element.
Sample Solution:
Python Code:
import numpy as np
nums = np.random.rand(5, 5)
print("Original array elements:")
print(nums)
exp_arr = np.exp(nums)
print("\nExponential of each element of the said array:")
print(exp_arr)
Sample Output:
Original array elements: [[0.36959613 0.61718307 0.51482027 0.54201977 0.47885604] [0.96237425 0.86653443 0.99702202 0.20504792 0.10261349] [0.47008673 0.46721343 0.94903901 0.74238819 0.23236025] [0.06117178 0.13717994 0.18294167 0.25826883 0.87410313] [0.41298433 0.57386986 0.34611886 0.47406998 0.32508609]] Exponential of each element of the said array: [[1.44715003 1.85369893 1.67333772 1.7194763 1.61422673] [2.61790465 2.37865316 2.71019888 1.22758388 1.10806305] [1.60013297 1.5955419 2.58322601 2.10094699 1.26157413] [1.06308151 1.14703452 1.20074437 1.29468682 2.39672477] [1.51132134 1.77512325 1.41357063 1.6065194 1.3841498 ]]
Explanation:
In the above exercise -
nums = np.random.rand(5, 5): This line creates a NumPy array of shape (5, 5) with random values generated from a uniform distribution between 0 and 1.
exp_arr = np.exp(nums): This line calculates the exponential function for each element in nums. The exponential function exp(x) is defined as e^x, where e is Euler's number (approximately 2.71828). In this case, the function is applied element-wise to the entire array, resulting in a new array with the same shape as nums, where each element is the exponential function of the corresponding element in nums.
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Replace the minimum value with 0 in a 5x5 array with random values.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Python: Tips of the Day
Decapitalizes the first letter of a string:
Example:
def tips_decapitalize(s, upper_rest=False): return s[:1].lower() + (s[1:].upper() if upper_rest else s[1:]) print(tips_decapitalize('PythonTips')) print(tips_decapitalize('PythonTips', True))
Output:
pythonTips pYTHONTIPS
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook