Random Numbers

If you give the same input your program will generate the same output every time, so we say these programs are deterministic. Determinism is a good thing since we expect the same calculation to yield the same result. There are some applications that we want the computer to be unpredictable. For example games are non-deterministic.
Creating a program that is nondeterministic is not so easy, but there are ways to make it as close as nondeterministic with use of algorithms that generate pseudorandom numbers. As the name suggest pseudorandom numbers are not truly random because they are generated using deterministic computation.
The random function is built-in Python module that provides functions which generate pseudorandom numbers. The function random returns a random number between 0.0 and 1.0. Each time you call random function, you get the different number.
Example of running random functions is given below:
>>> import random
>>> for i in range(10):
...     x = random.random()
...     print x
...
0.72691741702
0.553781322679
0.184009175528
0.23973370468
0.691981899444
0.447441488044
0.00103890022077
0.683243270148
0.0845186417364
0.019750204009
In previous example we’ve used for loop so be sure to check out the next section called Iteration??? Program produced list of 10 numbers of float type between 0.0 up to 1.0.
The random function is one of the many functions which handle random numbers. The function randint takes parameters low and high and returns an integer between low and high. The example of randint functions is given below.
>>> random.randint(4,10)
6
>>> random.randint(5,230)
94
To choose an element form defined sequence use built-in function choice:
>>> t=[1,2,3]
>>> random.choice(t)
3
>>> random.choice(t)
3
>>> random.choice(t)
3
>>> random.choice(t)
2
>>> random.choice(t)
1

Nema komentara:

Objavi komentar