[Tutor] list noise [not what you think]
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Thu, 7 Feb 2002 22:13:57 -0800 (PST)
On Fri, 8 Feb 2002, kevin parks wrote:
> Is there a way to fill a list with random values? I'd like to make a
> list and fill it with either white noise, pink noise, or brownian
> values, and then later (hopefully) filter and quantize them. Does
> Python have these different kinds of noise generators built in or as
> part of some standard module?
Hi Kevin,
We seem to be getting a lot of random questions lately! *grin*
Yes, there are several good ways of doing this. The easy ways will use
the 'random' module, and we can find documentation about it here:
http://www.python.org/doc/current/lib/module-random.html
The documentation is a bit terse, but it does show that we can use
something like random.random() to get random floating-point numbers
between 0 and 1. Here's an interpreter session that demonstrates this
function:
###
>>> from random import random
>>> random()
0.913230480874057
>>> random()
0.35874922590195979
>>> random()
0.28924989831892356
>>> random()
0.11919278512468923
###
By using random.random() with some list manipulation, we can quickly build
up a list of random values. Dman's example uses array assignment, which
is a very good way of building the list. A similar way of doing it is by
list append()ing:
###
def makeRandomList(n):
"""Returns a list of n random numbers, where each entry
is a float somewhere in [0, 1)."""
mylist = []
for i in xrange(n) :
mylist.append(random.random())
return mylist
###
But the basic idea is the same: we call random.random() repeatedly and
assign each to a new spot in our list.
There are more sophisticated functions in the 'random' module, including
stuff to generate normal, gamma, and gaussian distributions. I need to
brush up on a statistics book to figure out what those terms mean!
*grin*
Good luck to you.