NumPy: Create a vector of size 10 with values ranging from 0 to 1, both excluded
NumPy: Array Object Exercise-66 with Solution
Write a NumPy program to create a vector of size 10 with values ranging from 0 to 1, both excluded.
Pictorial Presentation:
Sample Solution:
Python Code:
# Importing the NumPy library and aliasing it as 'np'
import numpy as np
# Creating an array 'x' using NumPy's linspace function,
# generating 12 evenly spaced values between 0 and 1 (inclusive) with the 'endpoint' set to True,
# and selecting elements from index 1 to the second-to-last index using [1:-1]
x = np.linspace(0, 1, 12, endpoint=True)[1:-1]
# Printing the array 'x' that was created
print(x)
Sample Output:
[ 0.09090909 0.18181818 0.27272727 0.36363636 0.45454545 0.5454545 5 0.63636364 0.72727273 0.81818182 0.90909091]
Explanation:
In the above code –
x = np.linspace(0,1,12,endpoint=True): This line creates a 1D NumPy array with 12 evenly spaced values between 0 and 1 (both inclusive). The endpoint=True parameter ensures that the endpoint (1) is included in the array. The resulting array would look like this: [0., 0.09090909, 0.18181818, ..., 0.81818182, 0.90909091, 1.].
[1:-1]: This slice notation is applied to the array x to remove the first element (0.) and the last element (1.) of the array. The resulting array would look like this: [0.09090909, 0.18181818, ..., 0.81818182, 0.90909091].
print(x): This line prints the modified array after removing the first and the last elements: [0.09090909, 0.18181818, ..., 0.81818182, 0.90909091].
Python-Numpy Code Editor:
Previous: Write a NumPy program to test if specified values are present in an array.
Next: Write a NumPy program to make an array immutable (read-only).
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/numpy/python-numpy-exercise-66.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics