Generating Arrays Using arange() and linspace() in NumPy Framework
NumPy provides the arange()
and linspace()
functions to generate numerical sequences efficiently. These functions are useful for creating ranges of numbers for computations and plotting.
1. Generating Arrays Using np.arange()
The np.arange()
function generates arrays with regularly spaced values within a given range.
import numpy as np # Creating an array from 0 to 9 with step 1 arr1 = np.arange(10) print(arr1) # Creating an array from 1 to 10 with step 2 arr2 = np.arange(1, 10, 2) print(arr2)
Output:
[0 1 2 3 4 5 6 7 8 9] [1 3 5 7 9]
2. Generating Arrays Using np.linspace()
The np.linspace()
function generates an array of evenly spaced numbers over a specified range.
# Creating an array of 5 values between 0 and 1 lin_arr1 = np.linspace(0, 1, 5) print(lin_arr1) # Creating an array of 7 values between 10 and 50 lin_arr2 = np.linspace(10, 50, 7) print(lin_arr2)
Output:
[0. 0.25 0.5 0.75 1. ] [10. 16.67 23.33 30. 36.67 43.33 50. ]
3. Key Differences Between arange()
and linspace()
- arange(): Uses a step value and may not always include the stop value due to floating-point precision.
- linspace(): Uses a specified number of points and always includes the stop value.
Conclusion
Both arange()
and linspace()
are useful for generating numerical sequences. arange()
is ideal for sequences with a fixed step size, while linspace()
ensures precise spacing between points.