SciPy Recipes
上QQ阅读APP看书,第一时间看更新

Creating arrays with equally spaced values

There are two NumPy functions that create arrays with equally spaced elements: arange() and linspace(). The arange() function, which stands for array range, has an interface similar to the built-in Python range() function, except that the arguments can be floats, as shown in the following example:

x = np.arange(1.1, 1.9, 0.2)

This generates an array with elements between 1.1 and 1.9, with increments of 0.2, resulting in the array as follows:

array([ 1.1,  1.3,  1.5,  1.7])

Notice that the right endpoint is not included, that is, arange() uses the same convention as range(). As in the built-in Python range() function, the increment can be omitted, and is then assumed to be equal to 1, as demonstrated in the following code:

x = np.arange(2.5, 6.5)

Here, only the start and end point of the range is given, producing the array:

array([ 2.5,  3.5,  4.5,  5.5])

If only one argument is given, the initial point is assumed to be zero and the increment is assumed to be one, as shown in the following code:

x = np.arange(3.2)

This statement will generate the following array:

array([ 0.,  1.,  2.,  3.])

All the preceding examples generate ranges with the float64 element type. To generate a range with a different type, we can either use integer arguments in the function call, or specify the dtype option, as shown in the following example:

x = np.arange(0.9, 4.9, dtype=np.int64)

This statement, somewhat surprisingly, generates the following array:

array([0, 1, 2, 3])

To understand the output, notice that when generating the array range, NumPy will first cast the functions argument to the int type, which always rounds towards 0. So, the preceding range is effectively identical to the following:

x = np.arange(0, 4)

An alternative to arange() is the linspace() function, which is illustrated in the following example:

x = np.linspace(1.2, 3.2, 11)

This statement generates an array of 11 equally spaced floats from 1.2 to 3.2, including both endpoints, producing the array as follows:

array([ 1.2,  1.4,  1.6,  1.8,  2. ,  2.2,  2.4,  2.6,  2.8,  3. ,  3.2])