Do you wish to learn how to generate a float range of numbers in Python? In this tutorial, you will find many ways to produce floating point values within a given range. We’ve provided several Python programming examples here so that you can easily understand the logic.
Generate Float Range in Python
This tutorial describes different ways to generate float values. You should also be able to specify a float type value for start/stop/step arguments of the custom range function.
We recommend you should at least use Python 3 for writing code and run examples. Python 2 is still getting updates, but newer versions are more stable and advanced.
What does the Python range function lack?
Python range can only generate a set of integer numbers from a given band. Neither does it allow a float type parameter nor it can produce a float range of numbers.
It accepts one, two, or three parameters (start/stop/step). However, all arguments are of integer type. If you pass a float, it results in a TypeError.
start = 1 stop = 6.7 step = 0.1 for value in range(start, stop, step): print (value)
When you run the above code, it throws the following error:
TypeError: 'float' object cannot be interpreted as an integer
The above example suggests that Python doesn’t give any built-in way to generate a floating point range. Therefore, we need to devise a custom implementation of the range function.
Why does Python range not allow a float?
Python range function generates a finite set of integer numbers. You can determine the size by subtracting the start value from the stop value (when step = 1). Below is the general formula to compute the length.
# Formula to calculate the length of items returned by Python range function (stop - start)//step + 1
Check some examples to get clarity.
>>> len(list(range(1,10,2))) 5 >>> 10-1/2 + 1 >>> (10-1)//2 + 1 5
However, the same range virtually has an infinite no. of float numbers. You can restrict it by using a fixed precision value. Hence, it could be possibly the reason for range() not allowing floats.
Using yield to generate a float range
You can write a custom Python function like the one below. It can let you specify a float value for the step argument.
import decimal def float_range(start, stop, step): while start < stop: yield float(start) start += decimal.Decimal(step) print(list(float_range(0, 1, '0.1')))
The output is as follows:
[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
We’ve used the decimal module to keep the precision fixed.
At this point, we want to bring your attention to 100+ Python interview questions, one of the most-read resources on our blog. Consider reading these questions once you complete this tutorial.
NumPy arange()
function for a range of floats
To use arange()
function, you need to install and import the NumPy package. This library has various arithmetic and numeric functions to generate arrays/matrices of different sizes.
Anyways, we’ll here use the arange()
function for generating a range of float numbers.
It has the same signature as the built-in range method. But we can pass float arguments as parameters to this function.
# Syntax import numpy arange (start, stop, step)
Now, let’s go through some examples to improve our understanding.
from numpy import arange print("NumPy arange():") print("\nTest 1:") for i in arange(0.0, 1.0, 0.1): print(i, end=', ') print("\n\nTest 2:") for i in arange(0.5, 5.5, 0.5): print(i, end=', ') print("\n\nTest 3:") for i in arange(-1.0, 1.0, 0.5): print(i, end=', ')
The output is as follows:
NumPy arange(): Test 1: 0.0, 0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6000000000000001, 0.7000000000000001, 0.8, 0.9 Test 2: 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0 Test 3: -1.0, -0.5, 0.0, 0.5
NumPy linspace
function to generate a float range
NumPy has another method (linspace()
) to let you produce the specified no. of float numbers. It has the following syntax:
# Syntax linspace(start, stop, num, endpoint) start => starting point of the range stop => ending point num => Number of values to generate, non-negative, default value is 50. endpoint => Default value is True. If True, includes the stop value else ignores it.
This function has more arguments, but we described the ones that fulfill our purpose.
Check out the below examples.
import numpy as np print("Using NumPy LinSpace()\n") print(np.linspace(1.0, 5.0, num = 5)) print(np.linspace(0, 10, num = 5, endpoint = False))
The output is as follows:
Using NumPy LinSpace() [1. 2. 3. 4. 5.] [0. 2. 4. 6. 8.]
If you don’t wish to install the NumPy package, then try the approach in the next example.
Generate float range without a built-in function
Here, we have provided a simple Python program to generate the range of float numbers. It accepts both +ve and -ve values for arguments.
This example has 2 logical divisions. The first defines the function float_range(). Another one calls it with different input values and prints the result.
""" Desc : This function generates a float range of numbers w/o using any library. Params : A (int/float) : First number in the range L (int/float) : Last number in the range D (int/float) : Step or the common difference """ def float_range(A, L=None, D=None): #Use float number in range() function # if L and D argument is null set A=0.0 and D = 1.0 if L == None: L = A + 0.0 A = 0.0 if D == None: D = 1.0 while True: if D > 0 and A >= L: break elif D < 0 and A <= L: break yield ("%g" % A) # return float number A = A + D #end of function float_range() """ Desc: This section calls the above function with different test data. """ print ("\nPrinting result") print ("\nTest 1: ", end = " ") for i in float_range(0.1, 5.0, 0.5): print (i, end=", ") print ("\nTest 2: ", end = " ") for i in float_range(-5.0, 5.0, 1.5): print (i, end=", ") print ("\nTest 3: ", end = " ") for num in float_range(5.5): print (num, end=", ") print ("\nTest 4: ", end = " ") for num in float_range(10.1, 20.1): print (num, end=", ")
The output is as follows:
Printing result Test 1: 0.1, 0.6, 1.1, 1.6, 2.1, 2.6, 3.1, 3.6, 4.1, 4.6, Test 2: -5, -3.5, -2, -0.5, 1, 2.5, 4, Test 3: 0, 1, 2, 3, 4, 5, Test 4: 10.1, 11.1, 12.1, 13.1, 14.1, 15.1, 16.1, 17.1, 18.1, 19.1,
Using float value in step parameter
In a custom range function, we can provide a float type value as the step argument. It will then allow us to generate numbers in a particular interval.
Let us check out an example that specifies 3.7 as the step value.
import numpy as pynum_float print("Display range using a float value in the step\n", pynum_float.arange(3, 33, 3.7))
The output is as follows:
Display range using a float value in the step [ 3. 6.7 10.4 14.1 17.8 21.5 25.2 28.9 32.6]
Generate float range using itertools
The itertools module provides islice()
and count()
functions. Check out the below example where we’ve coded a simple method to produce float values.
from itertools import islice, count def iter_range(start, stop, step): if step == 0: raise ValueError("Step could not be NULL") length = int(abs(stop - start) / step) return islice(count(start, step), length) for it in iter_range(0, 10, 1.10): print ("{0:.1f}".format(it), end = " ")
The output is as follows:
0.0 1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8
Summary
We wish you have now learned how to generate a range of floating point numbers. You can choose any of the methods explained above and use them in your assignments.
You may now look for further topics such as how to generate random numbers in Python.