Range () with step float argument

Possible duplicate:
Python decimal range value ()

I would like to create a list like this:

[0, 0.05, 0.1, 0.15 ... ] 

the range (0, 1, 0.05) will be large, but this does not work:

range () the integer step argument expected to receive a float.

Do you have any elegant idea?;)

+6
source share
5 answers

If you can use numpy, numpy.linspace recommended. Functions that try to accommodate range logic in floating point numbers, including numpy own arange , are usually confused as to whether the ending border in the list ends or not. linspace elegantly decides that if you explicitly specify a start point, an end point, and the required number of elements:

 >>> import numpy >>> numpy.linspace(0.0, 1.0, 21) array([ 0. , 0.05, 0.1 , 0.15, 0.2 , 0.25, 0.3 , 0.35, 0.4 , 0.45, 0.5 , 0.55, 0.6 , 0.65, 0.7 , 0.75, 0.8 , 0.85, 0.9 , 0.95, 1. ]) 
+6
source

In Python 3, a range returns a generator (immutable sequence) ... so I think we can define a very simple function, for example:

 def frange(start,stop, step=1.0): while start < stop: yield start start +=step 

So:

 for x in frange(0, 1, 0.05): print(x) 

Python doesn't have to be complicated.

If you need a list, just call:

 list(frange(0,1,0.05)) 

Or change the function to immediately return the list.

You can use single-line solutions that multiply or do other things, but it can be difficult with different start and end values. If you often use such ranges, just use this function and reuse it. Even single-line repetition, repeatedly repeated by code, is bad.

+3
source

Or how about this:

 [v*0.05 for v in range(0,int(1/0.05))] 
+2
source

How about this:

 temp = range(0,100,5) # 0,5,10,...,95 final_list = map(lambda x: x/100.0,temp) # becomes 0,0.05,0.10,...,0.95 

It is not very elegant, but I never worried about creating the proper function. In addition, it only works if the step size is rational. The advantage is that it is fast enough to be done locally.

See the comments on your OP for a more general and more elegant solution.

+1
source

what happened with

 [i/100.0 for i in range(0, 100, 5)] 

? You check how many digits you want (there are two here) and select a suitable factor (1 becomes 100, 0.05 equals 5).

+1
source

Source: https://habr.com/ru/post/925292/


All Articles