There are sometimes when you need to generate a range of floating-point numbers, for making various codes easier to implement and execute. Here, the focus is on generating a range of floating-point numbers.
This tutorial demonstrates the several methods available to generate a range of float-point numbers.
Table of Contents
What is a floating-point number in Python?
A floating-point number, typically categorized and stored under the float
data type, is capable of representing real numbers that contain both integer and fractional parts. A float
can store numbers containing decimal points without any errors or loss of data.
Why not use the simple and popular range()
function?
To simply carry out the operation of returning a sequence of numbers in Python, we typically use the range()
function. However, the range()
function is not applicable for use with the floating-point numbers and is incapable of accepting a floating-point number as its input.
If a floating-point number is entered as an input to the function, it automatically generates an error that displays the words TypeError
.
Python range float : How to generate floating-point numbers in Python?
- Using
numpy.linspace()
method. - Using
numpy.arange()
method. - Using list comprehension.
- Using generator comprehension.
- Using yield generator.
- Using a user-defined function
- Using the
itertools
module and its functions. - Using the
map()
function along with alambda
function. - Using
round()
function.
Using the numpy.linspace()
method.
The numpy.linspace()
method takes in the start
and stop
values and moves on to return a sequence of numbers as specified by the user.
Further specifications on this function are done by specifying the num
argument that the function takes in, which is utilized to specify the number of values that need to be generated within the given range.
This method comes under the NumPy
library, which is utilized in dealing with arrays and matrices and needs to be imported to the Python code before using this method.
The following code uses the numpy.linspace()
method to generate a range of float-point numbers in Python.
1 2 3 4 5 |
import numpy as np x = np.linspace(0, 1, 10, endpoint=0) print(x) |
The above code provides the following output:
As seen in the above code, the endpoint
argument can be optionally specified according to a particular user’s needs. This argument states whether the final value of the sequence needs to be included or not, and holds a default value of 0
.
Using the numpy.arange()
method.
The numpy.arange()
method, similar to the numpy.linspace()
method, takes in the start
and stop
values and moves on to return a sequence of numbers as specified by the user. However, instead of the num
argument, the numpy.arange()
method takes in another step
argument that is utilized to specify the step size between the sequence.
By default, start
holds the value 0
while stop
holds the value 1
.
This method comes under the NumPy
library and is not a default Python function, which means it is necessary to import the NumPy
library to the Python code before using this method.
The following code uses the numpy.arange()
method to generate a range of float-point numbers in Python.
1 2 3 4 5 |
import numpy as np x = np.arange(0, 1, 0.1) print(x) |
The above code provides the following output:
Using list comprehension.
List comprehension is a relatively shorter and very graceful way to create lists that are to be formed on the basis of given values of an already existing list.
This method makes a set of tweaks to enable implementing the given task with the help of the range()
method.
With the help of list comprehension, we compactly divide all the results of the original range()
function and convert it to the decimal form. Here, we divide the outcome of the range()
function by 10 to keep things simple to understand, but any other number can be used instead.
The following code uses list comprehension to generate a range of float-point numbers in Python.
1 2 3 4 |
x = [i/10 for i in range(0, 10)] print(x) |
The above code provides the following output:
Using generator comprehension.
Generator comprehension works in a similar manner to list comprehension and uses a compact and syntactic approach in order to create an iterable generator object. The whole sequence can be looked at and generated with the help of the for
loop along with Generator comprehension.
The following code uses generator comprehension to generate a range of float-point numbers in Python.
1 2 3 4 5 6 |
x = (i/10 for i in range(0, 10)) for i in x: print(i, end= " ") print(x) |
The above code provides the following output:
Using yield generator.
A simple iterable generator object can be further accessed and implemented with the help of generator comprehension. However, the yield generator is a significantly superior and reusable way for generating the range of floating-point values with the help of the three arguments start
, stop
and step
.
The following code uses the yield keyword to create and implement a generator function that generates a range of float-point numbers in Python.
1 2 3 4 5 6 7 8 |
import decimal def float_range(sta, sto, stp): while sta < sto: yield float(sta) sta += decimal.Decimal(stp) print(list(float_range(0, 1, '0.1'))) |
The above code provides the following output:
Using a user-defined function.
Instead of importing different modules and utilizing several functions from them, we can simply think of a logic and create a user-defined function that implements the given task.
The following code creates a user-defined function and uses it to generate a range of float-point numbers in Python.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
def fl_range(A, L=None, D=None): 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) A = A + D print ("\nPrinting") print ("\nTest: ", end = " ") for x in fl_range(0.1, 1.0, 0.1): print (x, end=", ") print(fl_range(0.1, 1.0, 0.1)) |
The above code provides the following output
Test: 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1
Using the itertools
module and its functions.
The itertools
module is a built-in model which is frequently used in the world of Python programming and it contains several function that enables us to work on iterators to generate complex iterators.
To implement the task of generating a sequence of floating-point numbers, we will use the islice()
method from the arsenal of methods provided by the itertools
module.
The following code uses the islice()
method from the itertools
module to generate a range of float-point numbers in Python.
1 2 3 4 5 6 7 8 9 10 11 |
from itertools import islice, count def irange(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 x in irange(0, 1, 0.1): print ("{0:.1f}".format(x), end = " ") print(irange(0, 1, 0.1)) |
The above code provides the following output:
Using the map()
function along with a lambda function
.
The map()
function is provided by Python and it can be utilized to seek a particular specified function to all the existing elements in any given iterable. It produces the result as the iterator itself.
A lambda function can simply be defined as a compact anonymous function that is capable of taking any number of arguments while consisting of only a single expression.
The following code uses the map()
function along with the lambda function
to generate a range of float-point numbers in Python.
1 2 3 4 5 6 |
print(list(map(lambda val: val/10.0, range(1, 10, 1)))) RL = list(map(lambda val: val/10.0, range(1, 10, 1))) for x in RL: print(x,end=",") |
The above code provides the following output:
Using the round()
function.
The round()
function is an in-built function in Python that is utilized to round off the number given as the argument to a floating-point number.
The number of decimals can also be specified with this method, with the default value being 0
.
The round()
function, therefore, takes in two arguments and its syntax looks like this.
1 2 3 |
round(number, digits) |
Moving on, let us now see how we can use this function to generate a range of float-point numbers in Python.
1 2 3 4 |
x = [(round(i* 0.10,2)) for i in range(1,10)] print(x) |
The above code provides the following output:
That’s all about Python range float.