Can I increase from 0 to 1 by 0.1 by using range()?
Since you write range(0,1,0.1)
, the step can only receive an integer.
for i in range(0, 1, 0.1):
print i
for i in range(0,1,0.1): TypeError: range() integer step argument expected, got float.
python floating-point rage
range
and xrange
both step
can only receive int
You have to use a different method.
NumPy is not a Python standard library,
Allow This method seems to work normally in fori in myrange()
If you save it as a list, a round-off error occurs, so you have to write it carefully.step
to float
in range() with range() and similar functions. p>
import numpy
mylist = numpy.arange(0, 1, 0.1)
print mylist #[ 0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]
def myrange(start, end, step):
r = start
while(r<end):
yield r
r += step
for i in myrange(0,1,0.1):
print i
mylist = [ i for i in myrange(0,1,0.1)]
print mylist #[0, 0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6, 0.7, 0.7999999999999999, 0.8999999999999999, 0.9999999999999999]
The main limitation of python’s range() is it works only with integers. Python range() doesn’t support the float type.
I am not writing code here this article explained in the best way. you need to write your custom range() function which returns a range of float numbers. Python range() for float numbers
© 2024 OneMinuteCode. All rights reserved.