- Range of Floats in Python: A Step-by-Step Guide (3 Ways to Do It)
- Problem: Python range() Function Doesn’t Work with Floats
- Solution 1: Divide Each Number in the Range
- Solution 2: NumPy arrange()
- Problem with the arange()
- Solution 3: NumPy linspace()
- Conclusion
- Further Reading
- Генерация диапазона с плавающей запятой в Python
- Чего Не Хватает В Функции Диапазона Python?
- Почему Python range() не работает с float?
- Использование Yield для генерации диапазона с плавающей запятой
- Функция NumPy Arange() для диапазона значений с плавающей запятой
- Функция NumPy Linspace для генерации диапазона с плавающей запятой
- Генерация диапазона с плавающей запятой без использования сторонних модулей
- Использование значения с плавающей запятой в параметре step
- Создать диапазон с плавающей запятой, используя Itertools
- Резюме
Range of Floats in Python: A Step-by-Step Guide (3 Ways to Do It)
To create a range of floats in Python, use list comprehension.
For example, to create a range of floats from 0 to 1 with a 1/10th interval:
rng = [x / 10 for x in range(0, 10)] print(rng)
[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
In this guide, you will see some alternative approaches to creating a range of floats in Python.
Problem: Python range() Function Doesn’t Work with Floats
In Python, the built-in range() function can be used to generate a range of values between m and n .
numbers = range(1, 6) # 1, 2, 3, 4, 5
However, the range is supposed to consist of integers only.
This means you cannot have a range() call like this:
A call like this would produce an error that warns you about misusing the range() function.
Solution 1: Divide Each Number in the Range
To overcome the issue of the range() function not working with floats, you can produce a range and divide each number in that range to get a range of floats.
For example, let’s generate a list that represents floats between the range 0.0 and 1.0:
numbers = range(0, 10) float_nums = [] for number in numbers: f = number / 10 float_nums.append(f) print(float_nums)
[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
This for loop can be expressed in a smoother way using a list comprehension:
rng = [x / 10 for x in range(0, 10)] print(rng)
However, it gets a bit tricky when you want to produce other types of ranges.
For example, producing a list of numbers from 1.5 to 4.25, with 0.25 intervals using a for loop already requires some thinking. Needless to mention when the numbers are not evenly divisible.
This is where NumPy library can help you.
Solution 2: NumPy arrange()
Another option to produce a range of floats is to use the NumPy module’s arange() function.
This function follows the syntax:
numpy.arange(start, stop, step)
- start is the starting value of the range.
- stop specifies the end of the range. The stop is not included in the range!
- step determines how big steps to take when generating the range.
In case you do not have NumPy installed, you can install it with PIP by running the following command in the command line:
Now that you have the library, you can use the arange() function to generate a range of floats:
import numpy as np rng = np.arange(0.0, 1.0, 0.1) print(rng)
[ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
Notice how this range is exclusive as it does not include the end value 1.0 in the range.
To make the range inclusive, add one step size to the stop parameter.
For example, to generate a range of floats from 0.0 to 1.0:
import numpy as np start = 0.0 stop = 1.0 step = 0.1 rng = np.arange(start, stop + step, step) print(rng)
[0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. ]
Problem with the arange()
The problem with the arange() approach is the floating-point rounding errors.
For example, this creates an array of four values (1, 1.1, 1.2, 1.3), even though it should produce only three values (1, 1.1, 1.2):
import numpy as np rng = np.arange(1, 1.3, 0.1) print(rng)
Solution 3: NumPy linspace()
To overcome the floating-point rounding issues with the numpy’s arange() function, use numpy’s linspace() function instead.
Notice, however, that this function behaves differently. It asks how many numbers you want to linearly space between a start and an end value.
numpy.linspace(start, stop, nvalues)
- start is the starting value of the range.
- stop is the ending value of the range.
- nvalues is the number of values to generate in-between start and stop.
For example, let’s generate values from 0.0 to 1.0 with 0.1 intervals. This means the start is 0 and the end is 1. Also, notice you want 11 values in total.
Here is how it looks in the code:
import numpy as np rng = np.linspace(0, 1, 11) print(rng)
[0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. ]
Conclusion
To create a range of floats in Python, you cannot use the range() function directly. This is because the range() function only supports integers. To overcome this problem, you have a couple of options:
Thanks for reading. Happy coding!
Further Reading
Генерация диапазона с плавающей запятой в Python
Вы хотите узнать, как генерировать диапазон чисел с плавающей запятой в Python? В этом руководстве вы найдете много способов получения значений с плавающей запятой в пределах заданного диапазона.
Мы рекомендуем вам по крайней мере использовать Python 3 для написания кода и запуска примеров. Python 2.x все еще получает обновления, но более новые версии более стабильны и продвинуты.
Чего Не Хватает В Функции Диапазона Python?
Диапазон Python может генерировать только набор целых чисел из данной полосы. Он также не допускает параметр типа с плавающей запятой и не может генерировать диапазон чисел с плавающей запятой.
Он принимает один, два или три параметра (старт / стоп / шаг). Однако все аргументы имеют целочисленный тип. Если вы передадите float, это приведет к ошибке TypeError.
start = 1 stop = 6.7 step = 0.1 for value in range(start, stop, step): print (value)
Когда вы запускаете приведенный выше код, он выдает следующую ошибку:
TypeError: 'float' object cannot be interpreted as an integer
Приведенный выше пример предполагает, что Python не предоставляет встроенного способа генерации диапазона с плавающей запятой. Поэтому нам нужно разработать собственную реализацию функции range.
Почему Python range() не работает с float?
Функция range генерирует конечный набор целых чисел. Вы можете определить размер, вычитая начальное значение из конечного значения (когда шаг = 1). Ниже приведена общая формула для расчета длины.
Проверьте примеры приведенные ниже, чтобы получить ясность.
>>> len(list(range(1,10,2))) 5 >>> 10-1/2 + 1 >>> (10-1)//2 + 1 5
Однако тот же диапазон фактически имеет бесконечное количество из чисел с плавающей запятой. Вы можете ограничить его, используя фиксированное значение точности. Следовательно, это может быть возможной причиной того, что range() не позволяет работать с float.
Использование Yield для генерации диапазона с плавающей запятой
Вы можете написать пользовательскую функцию Python, как показано ниже. Это может позволить вам указать значение с плавающей запятой для аргумента шага.
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')))
[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
Мы использовали модуль decimal для сохранения точности.
Функция NumPy Arange() для диапазона значений с плавающей запятой
Чтобы использовать функцию arange(), вам необходимо установить и импортировать пакет numpy. Эта библиотека имеет различные арифметические и числовые функции для генерации массивов / матриц разных размеров.
В любом случае, здесь мы будем использовать функцию arange() для генерации диапазона чисел с плавающей запятой.
Arange() имеет ту же сигнатуру, что и встроенный метод range. Но мы можем передать аргументы типа float (с плавающей запятой) в качестве параметров этой функции.
# Syntax import numpy arange(start, stop, step)
Теперь давайте рассмотрим пример, чтобы улучшить наше понимание.
from numpy import arange print("Float range using 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=', ')
Float range using 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 для генерации диапазона с плавающей запятой
У NumPy есть другой метод linspace(), позволяющий вам создать указанное количество чисел с плавающей запятой. Он имеет следующий синтаксис:
# 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.
Эта функция имеет больше аргументов, но мы описали те, которые соответствуют нашей цели.
Посмотрите на приведенные ниже примеры.
import numpy as np print("Print Float Range Using NumPy LinSpace()\n") print(np.linspace(1.0, 5.0, num = 5)) print(np.linspace(0, 10, num = 5, endpoint = False))
Print Float Range Using NumPy LinSpace() [1. 2. 3. 4. 5.] [0. 2. 4. 6. 8.]
Если вы не хотите устанавливать пакет NumPy, попробуйте подход в следующем примере.
Генерация диапазона с плавающей запятой без использования сторонних модулей
Здесь мы предоставили простую программу на Python для генерации диапазона чисел с плавающей запятой. Он принимает как положительное так и отрицательное значение для аргументов.
Этот пример имеет 2 логических деления. Первый определяет функцию float_range(). Другой вызывает его с разными входными значениями и печатает результат.
""" 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 APrinting float range 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,Использование значения с плавающей запятой в параметре step
В пользовательской функции диапазона мы можем предоставить значение типа с плавающей запятой в качестве аргумента шага. Это позволит нам генерировать числа в определенном интервале.
Давайте рассмотрим пример, в котором в качестве значения шага указано 3.7.
import numpy as pynum_float print( "Display range using a float value in the step\n", pynum_float.arange(3, 33, 3.7) )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]Создать диапазон с плавающей запятой, используя Itertools
Мы также можем использовать модуль itertools и его функции, такие как islice() и count. Посмотрите на приведенный ниже пример, где мы написали простой метод для создания диапазона.
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 ("".format(it), end = " ")0.0 1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8Резюме
Хотелось бы, чтобы вы узнали, как генерировать диапазон чисел с плавающей запятой. Вы можете выбрать любой из методов, описанных выше, и использовать его в своих задачах.