Joan Venge
Joan Venge

Reputation: 331270

Is there a built-in Python function to generate 100 numbers from 0 to 1?

I am looking for something like range, but one that will allow me to specify the start and the end value, along with how many numbers I need in the collection which I want to use in a similar fashion range is used in for loops.

Upvotes: 0

Views: 1118

Answers (4)

Raymond Hettinger
Raymond Hettinger

Reputation: 226524

Python doesn't have a floating point range function but you can simulate one easily with a list comprehension:

>>> lo = 2.0
>>> hi = 12.0
>>> n = 20
>>> [(hi - lo) / n * i + lo for i in range(n)]
[2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5, 10.0, 10.5, 11.0, 11.5]

Note, in numeric applications, people typically want to include both endpoints rather than have a half-open interval like Python's built-in range() function. If you need both end-points you can easily add that by changing range(n) to range(n+1).

Also, consider using numpy which has tools like arange() and linspace() already built in.

Upvotes: 7

Pavan Yalamanchili
Pavan Yalamanchili

Reputation: 12109

There is a special function in numpy to do this: linspace. Ofcourse you will have to install numpy first. You can find more about it here.

Upvotes: 2

juliomalegria
juliomalegria

Reputation: 24921

No, there is no built-in function to do what you want. But, you can always define your own range:

def my_range(start, end, how_many):
    incr = float(end - start)/how_many
    return [start + i*incr for i in range(how_many)]

And you can using in a for-loop in the same way you would use range:

>>> for i in my_range(0, 1, 10):
...     print i
... 
0.0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9

EDIT: If you want both start and end to be part of the result, your my_range function would be:

def my_range(start, end, how_many):
    incr = float(end - start)/(how_many - 1)
    return [start + i*incr for i in range(how_many-1)] + [end]

And in your for-loop:

>>> for i in my_range(0, 1, 10):
...   print i
... 
0.0
0.111111111111
0.222222222222
0.333333333333
0.444444444444
0.555555555556
0.666666666667
0.777777777778
0.888888888889
1

Upvotes: 3

Matt Ball
Matt Ball

Reputation: 359966

You can still use range, you know. You just need to start out big, then divide:

for x in range(100):
    print x/100.0

If you want to include the endpoint:

for x in range(101):
    print x/100.0

Upvotes: 2

Related Questions