0

I want to ask user to determine step size of a for-loop. User will write in input a float number, for example 0.2 or 0.5, but Python does not accept float in for-loop, so we must change it to integer.

for i in range (1, 3.5, 0.5): #This is proposal
   print(i)

for i in range (10, 35, 5): #This is the logical term for Python
   print(i/10)

If the user write 0.05 the ranges of loop must be 100 to 350 with step size 5 It means we multiplied 1 and 3.5 into 100 or for step size 0.5 we multiplied them into 10. then how should we do?

I mean when user write stepseize = 0.00005 we have 5 decimal numbers, so we must multiply 1 and 3.5 into a 1 which has 5 zeros in front of it, 100000. If user write stepseize = 0.0042 we have 4 decimal numbers and the we must multiply 1 and 3.5 into 10000

q = 100... # zeroes are in terms of number of decimals
for i in range (1*(q), 3.5*(q), n*q) : #This is the logical term for Python
   print(i/q)
David
  • 63
  • 11
  • 4
    Possible duplicate of [How to use a decimal range() step value?](https://stackoverflow.com/questions/477486/how-to-use-a-decimal-range-step-value) – Ofer Sadan May 24 '18 at 11:23
  • 2
    I definitively recommend using numpy's `arange`. It works similarly to range but can also deal with floats. If you do not want to use other packages, you will have to deal with "the many zeros in front of the number". – offeltoffel May 24 '18 at 11:28
  • @offeltoffel Thank you, is it slower or there are no differences in its speed with normal usage without numpy? – David May 24 '18 at 11:30
  • 1
    @David: numpy is usually faster than most numeric routines in regular python. – offeltoffel May 24 '18 at 11:31
  • @offeltoffel Thank you so much. – David May 24 '18 at 11:33

1 Answers1

0

You can write your own range generator that wraps the range() function but handles floats:

def range_floats(start,stop,step):
    f = 0
    while not step.is_integer():
        step *= 10
        f += 10
    return (i / f for i in range(start*f,stop*f,int(step)))

which works:

>>> for i in range_floats(0, 35, 0.5):
...     print(i)
... 
0.0
0.5
1.0
.
.
.
33.5
34.0
34.5
Joe Iddon
  • 18,600
  • 5
  • 29
  • 49