w3resource

NumPy: Create a vector of length 10 with values ​​evenly distributed between 5 and 50

NumPy: Basic Exercise-21 with Solution

Write a NumPy program to create a vector of length 10 with values ​​evenly distributed between 5 and 50.

The problem entails creating a NumPy program to generate a vector of length 10 with values evenly spaced between 5 and 50. This involves using NumPy's functionalities to create such a vector efficiently, ensuring that the values are distributed evenly within the specified range.

Sample Solution :

Python Code :

# Importing the NumPy library with an alias 'np'
import numpy as np

# Creating an array 'v' with length 5, evenly distributed values between 10 and 49 using np.linspace()
v = np.linspace(10, 49, 5)

# Printing a message indicating an array of length 5 with values evenly distributed between 10 and 49
print("Length 10 with values evenly distributed between 5 and 50:")

# Printing the array 'v'
print(v)

Output:

Length 10 with values evenly distributed between 5 and 50:
[ 10.    19.75  29.5   39.25  49.  ]                         

Explanation:

The numpy.linspace() function is used to create an array of evenly spaced numbers within a specified range. The range is defined by the start and end points of the sequence, and the number of evenly spaced points to be generated between them.

In the above code np.linspace() function creates a NumPy array 'v' containing evenly spaced numbers over the range from 10 to 49 (inclusive). The third argument, 5, specifies the number of samples to generate, which is 5 in this case.

print(v): This line prints the generated array to the console. The output will be an array containing 5 evenly spaced numbers between 10 and 49, e.g., [10. 19.75 29.5 39.25 49. ].

Visual Presentation:

NumPy: Create a vector of length 10 with values ​​evenly distributed between 5 and 50.

Python-Numpy Code Editor:

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

Previous: NumPy program to create a 3X4 array using and iterate over it.
Next: NumPy program to create a vector with values ​​from 0 to 20 and change the sign of the numbers in the range from 9 to 15.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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/basic/numpy-basic-exercise-21.php