Python - Float Range using NumPy


Float Range using NumPy in Python

By default, the built-in range class deals only with integers. But, if you would like to create a range with float values, you can do so by using NumPy library.

To create a Float Range in Python, you can use numpy.arange() function. The syntax of numpy.arange() function is given below.

numpy.arange(start, stop, step, dtype=None)

where

ParameterDescription
start[Optional] The start value of sequence. Default value is 0.
stopThe end value of the sequence. The sequence will stop before reaching this value.
step[Optional] The difference between consecutive values in the sequence. The default step is 1.
dtype[Optional] The data type of the elements in the array. If not specified, NumPy will infer the data type based on the values given in the input.

The function returns a NumPy array.

Examples

In the following examples, we create a sequence of float values using numpy.arange() function.

1. Create a Range with start=1.4, stop=2.8 in steps of 0.2

In the following program, we create a range with a specific start value of 1.4, stop value of 2.8, and a step value of 0.2.

Python Program

import numpy as np

my_range = np.arange(1.4, 2.8, 0.2)
print(my_range)

Output

[1.4 1.6 1.8 2.  2.2 2.4 2.6]

2. Create a Range with start=1.3 and stop=9.1

In this example, we create a range with a specific start value of 1.3, and a stop value of 9.1.

Since we have not given any step value, the default step value of 1 would take effect.

Python Program

import numpy as np

my_range = np.arange(1.3, 9.1)
print(my_range)

Output

[1.3 2.3 3.3 4.3 5.3 6.3 7.3 8.3]

3. Iterate over Float Range

numpy.arange() returns a NumPy Array. You can iterate over this array using a For loop, as shown in the following example.

Python Program

import numpy as np

my_range = np.arange(1.3, 9.1)

for i in my_range:
    print(i)

Output

1.3
2.3
3.3
4.299999999999999
5.299999999999999
6.299999999999999
7.299999999999998
8.299999999999999

Summary

In this tutorial of Python Ranges, we learned how to create a Range (a numpy array) with Float values using numpy.arange() function, with the help of examples.