w3resource

NumPy: Create a 1-D array of 30 evenly spaced elements between 2.5. and 6.5, inclusive


30 Evenly Spaced Values (2.5–6.5)

Write a NumPy program to create a 1-D array of 30 evenly spaced elements between 2.5 and 6.5, inclusive.

Sample Solution:

Python Code:

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

# Generating an array of 30 evenly spaced values from 2.5 to 6.5 inclusive
x = np.linspace(2.5, 6.5, 30)

# Printing the generated array
print(x)

Sample Output:

[ 2.5         2.63793103  2.77586207  2.9137931   3.05172414  3.1896551
7                                                                      
  3.32758621  3.46551724  3.60344828  3.74137931  3.87931034  4.0172413
8                                                                      
  4.15517241  4.29310345  4.43103448  4.56896552  4.70689655  4.8448275
9                                                                      
  4.98275862  5.12068966  5.25862069  5.39655172  5.53448276  5.6724137
9                                                                      
  5.81034483  5.94827586  6.0862069   6.22413793  6.36206897  6.5      
 ] 

Explanation:

In the above code -

x = np.linspace(2.5, 6.5, 30): This line creates a NumPy array x using the np.linspace() function. The function takes three arguments: the start value (2.5), the stop value (6.5), and the number of samples to generate (30). It generates a sequence of 30 evenly spaced values between the start and stop values, inclusive.

print(x): This line prints the array ‘x’ containing the 30 evenly spaced values between 2.5 and 6.5.


For more Practice: Solve these Related Problems:

  • Create a 1D array of 30 evenly spaced numbers between 2.5 and 6.5 using np.linspace and verify the endpoints.
  • Write a function that generates a linspace array and then applies a transformation to each element.
  • Check that the difference between consecutive elements remains constant throughout the array.
  • Validate the generated array by computing its mean and comparing it to the expected midpoint value.

Go to:


PREV : 1D Array (0–50) & (10–50)
NEXT : 20 Log-Spaced Values (2–5)


Python-Numpy Code Editor:

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.