How can i create a random array of floats from 0 to 5 in python

Oscar Benjamin oscar.j.benjamin at gmail.com
Tue Mar 12 17:59:29 EDT 2013


On 12 March 2013 20:21, llanitedave <llanitedave at veawb.coop> wrote:
> On Tuesday, March 12, 2013 10:47:25 AM UTC-7, Maarten wrote:
>> On Tuesday, March 12, 2013 6:11:10 PM UTC+1, Norah Jones wrote:
>>
>> > I want to create a random float array of size 100, with the values in the array ranging from 0 to 5. I have tried random.sample(range(5),100) but that does not work. How can i get what i want to achieve?
>>
>> Use numpy
[SNIP]
>
> While numpy would work, I fail to see how encouraging the op to download and install a separate library and learn a whole new set of tools would be beneficial by default, without knowing the purpose of the need.  This is like recommending an RPG to fix a sticky door hinge.

This suggestion comes after others that show how to use the stdlib's
random module. I don't think it's unreasonable to recommend numpy for
this. If you want to create *arrays* of random numbers then why not
use a library that provides an API specifically for that? You can test
yourself to see that numpy is 10x faster for large arrays:

Python 2.7 on Linux:
$ python -m timeit -s 'import random' -- '[random.uniform(0, 5) for x
in range(1000)]'
1000 loops, best of 3: 729 usec per loop
$ python -m timeit -s 'import random' -- '[random.random() * 5 for x
in range(1000)]'
1000 loops, best of 3: 296 usec per loop
$ python -m timeit -s 'import numpy' -- 'numpy.random.uniform(0, 5, 1000)'
10000 loops, best of 3: 32.2 usec per loop

I would use numpy for this mainly because if I'm creating arrays of
random numbers I probably want to use them in ways that are easier
with numpy arrays. There's also a chance the OP might benefit more
generally from using numpy depending on what they're working on.


Oscar



More information about the Python-list mailing list