In this article, we will see how to generate a range for float numbers in Python.

I have written a couple of example programs, which will demonstrate how to use a decimal value in a start, stop and step argument of custom `range()`

function to produce a range of floating-point numbers.

**Goals of this article**:

- Understand the limitation of Python’s
`range()`

function - Use numpy’s
and`arange()`

`linspace()`

functions to generate the range of float numbers - Use Python Generator to produce a
**range of float numbers without using any library**or module

Now, Let see one by one with the examples.

Recommended Exercise and Quiz:

**Further Reading**: **Python Basics (9 Article)**

Before moving to examples first understand the limitation of the built-in function `range()`

to handle decimal values.

## Limitation of Python’s range() function

The main limitation of Python’s range() is it **works only with integers**. It doesn’t support the float type i.e., we cannot use floating-point or non-integer numbers in any of its arguments. For example, Let’s see the following source code.

for num in range(0, 5.5, 0.1): print (num)

If you try to execute the above code Python will raise a `TypeError: 'float' object cannot be interpreted as an integer`

.

## Use numpy’s arange() function to generate the range for float numbers in Python.

We can use the NumPy library to get the range of floating-point numbers. NumPy library has various numeric functions and mathematical functions to operate on multi-dimensional arrays and matrices.

NumPy has the ** arange()** function to get the range of a floating-point number The

`arange()`

**function has the same syntax and functionality as a Python built-in**. Additionally, it also supports floating-point numbers in all of its arguments. i.e., we can pass float number in the start, stop and step arguments.

`range()`

function**Note**: NumPy doesn’t come with default Python installation. It is relatively easy to use. You can install it using pip.

`pip install numpy`

**Syntax of numpy’s arange() function**: –

arange (start, stop, step)

Let demonstrate the use with the following example.

import numpy print("Printing float range with numpy.arange()") print("Example one") for i in numpy.arange(0, 5.5, 0.5): print(i, end=', ') print("\nExample two") for i in numpy.arange(5.5, 15.5, 2.5): print(i, end=', ') print("\nExample Three") for i in numpy.arange(-2.5, 2.5, 0.5): print(i, end=', ')

**Output**: Run Online

Printing float range with numpy.arange() Example one 0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, Example two 5.5, 8.0, 10.5, 13.0, Example Three -2.5, -2.0, -1.5, -1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0,

### Use `numpy.linspace()`

function to get a range of float-numbers

The `numpy.linspace()`

**returns number spaces evenly w.r.t interval**. Similar to arange, but instead of step, it uses a sample number. This function doesn’t support negative numbers.

**Syntax**:

`linspace(start, stop, num, endpoint)`

**Parameters**:

`start`

: The starting number of the range by default, it starts with 0 if not specified.`stop`

: The end of the interval range.`num`

: Number of samples to generate, default is 50.`endpoint`

: Set it to False if you don’t’ want to include stop value in the result.

Let’s see the example.

import numpy as np print("Float Range Using linspace()\n") print("range from 2.5 to 12.5") for i in np.linspace(2.5, 12.5, num=5): print(i, end=', ') print("\n\nWithout including stop number in the result") print("range from 2.5 to 12.5") for i in np.linspace(2.5, 12.5, num=5, endpoint=False): print(i, end=', ')

**Output**:

Float Range Using linspace() range from 2.5 to 12.5 2.5, 5.0, 7.5, 10.0, 12.5, Without including stop number in the result range from 2.5 to 12.5 2.5, 4.5, 6.5, 8.5, 10.5,

**Note**: The `numpy.linspace()`

returns number spaces evenly w.r.t interval. so we cannot pass custom step value; instead, we can decide how many samples we want spaces evenly w.r.t interval.

**What to do if you don’t want to use the numpy library **just for

`arange()`

function? In this case, you can code your own function to generate a range of float numbers. Let’s see such examples.## The range for float numbers using Python Generator and yield

To get the range of float numbers ** without using NumPy and any library**, I have written a sample code that uses Generators and yield keyword to generate a range of floating-point numbers. This code works for both positive and negative float values.

The Following code divided into 2 Sections. the first section contains **function frange()**. another section tests custom `frange()`

function using the floating-point number with the following approaches.

- Positive float values in range() arguments.
- With negative float values in range() arguments.
- Negative and positive float step value in
`frange()`

arguments. - Generate float range in reverse order.

You can define a generator to replicate the behavior of Python built-in function `range()`

, which can accept floating-point numbers and produces a range of numbers.

**Let see the example now.**

def frange(start, stop=None, step=None): # if stop and step argument is None set start=0.0 and step = 1.0 start = float(start) if stop == None: stop = start + 0.0 start = 0.0 if step == None: step = 1.0 print("start= ", start, "stop= ", stop, "step= ", step) count = 0 while True: temp = float(start + count * step) if step > 0 and temp >= stop: break elif step < 0 and temp <= stop: break yield temp count += 1 print ("range for floating point numbers") for i in frange(1.5, 5.5, 0.5): print("%g" %i, end=", ") print ("\nUsing negative floating point numbers in range") for i in frange(-0.1, -0.5, -0.1): print("%g" %i, end=", ") print ("\nPrinting Reverse float range") for num in frange(0.5, 0.1, -0.1): print("%g" %num, end=", ") # Other test scenarios print ("\nPrinting float range") for num in frange(0, 7.5): print("%g" %num, end=", ") print ("\nPrinting float range") for num in frange(2.5, 7.5): print("%g" %num, end=", ")

**Output**: Run Online

range for floating point numbers start= 1.5 stop= 5.5 step= 0.5 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, Using negative floating point numbers in range start= -0.1 stop= -0.5 step= -0.1 -0.1, -0.2, -0.3, -0.4, Printing Reverse float range start= 0.5 stop= 0.1 step= -0.1 0.5, 0.4, 0.3, 0.2, Printing float range start= 0.0 stop= 7.5 step= 1.0 0, 1, 2, 3, 4, 5, 6, 7, Printing float range start= 2.5 stop= 7.5 step= 1.0 2.5, 3.5, 4.5, 5.5, 6.5,

### Generate a range of only positive float numbers using a generator

If you need a range of only positive float-numbers, you can try this code.

def frange_positve(start, stop=None, step=None): if stop == None: stop = start + 0.0 start = 0.0 if step == None: step = 1.0 print("start= ", start, "stop= ", stop, "step= ", step) count = 0 while True: temp = float(start + count * step) if temp >= stop: break yield temp count += 1 print("Using Positive float number in range function") for i in frange_positve(1.5, 10.5, 0.5): print("%g" %i, end=", ")

**Output**: Run Online

Using Positive float number in range function start= 1.5 stop= 10.5 step= 0.5 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6, 6.5, 7, 7.5, 8, 8.5, 9, 9.5, 10,

### Generate a range of only negative float numbers using a generator

If you need a range of only negative float-numbers, you can try this code.

def frange_negative(start, stop=None, step=None): if stop == None: stop = start + 0.0 start = 0.0 if step == None: step = 1.0 print("start= ", start, "stop= ", stop, "step= ", step) count = 0 while True: temp = float(start + count * step) if temp <= stop: break yield temp count += 1 print("\nUsing Negative float number in range function") for i in frange_negative (-0.1, -0.5, -0.1): print("%g" %i, end=", ")

**Output**: Run Online

Using Negative float number in range function start= -0.1 stop= -0.5 step= -0.1 -0.1, -0.2, -0.3, -0.4,

### Use float number in step argument of range() function

Same as integer step value, we can use a floating-point step in your custom range function. Using the float step size, you can generate floating-point numbers of a specific interval. Let see how to use a floating-point step in `numpy.arange()`

with an example program. In this example, the step value is 2.5.

import numpy as np print("Printing range using float step\n", np.arange(7, 25, 2.5) "\n")

You should get the following output.

Printing floating-point range with float step [ 7, 10, 12.5, 15, 17.5, 20, 22.5]

### Generate floating-point range using a itertools in Python

import itertools def seq(start, end, step): assert(step != 0) sample_count = int(abs(end - start) / step) return itertools.islice(itertools.count(start, step), sample_count) for i in seq(0, 1, 0.1): print ("%g" %i, end=", ")

Output:

0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9,

### Another example

The following code is useful for those who are not much familiar with python.

def seq_floats(start, stop, step=1): stop = stop - step; number = int(round((stop - start)/float(step))) if number > 1: return([start + step*i for i in range(number+1)]) elif number == 1: return([start]) else: return([]) print ("printing floating poinnt range for seq(1, 5, 0.5) -> ", seq_floats(1, 5, 0.5)) print ("printing floating poinnt range for seq(10, 0, -1) -> ", seq_floats(10, 0, -1)) print ("printing floating poinnt range for seq(10, 0, -2) -> ", seq_floats(10, 0, -2)) print ("printing floating poinnt range for seq(1,1) -> ", seq_floats(1,1))

Let execute the above code to get the range of positive and negative decimal point numbers.

Output:

printing floating poinnt range for seq(1, 5, 0.5) -> [1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5] printing floating poinnt range for seq(10, 0, -1) -> [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] printing floating poinnt range for seq(10, 0, -2) -> [10, 8, 6, 4, 2] printing floating poinnt range for seq(1,1) -> []

## Next Steps

To practice what you learned in this article, I have created a Python Basic **Quiz and Exercise**.

- Solve our
**Python essential exercise for beginners**to have a better understanding of Python’s basic concepts. - Solve our
**Basic Python Quiz for beginners**to test your fundamental Python skills.

Let me know your comments and feedback in the section below.