Sunday, October 8, 2017

Adventures in Python: Generating Random Numbers

Adventures in Python:  Generating Random Numbers

This program generates a list of random numbers between 0 and 1, using the pseudo-random number generator frac((π + t)^5). 

To use a pseudo-random number generator, you will need an initial seed.  This program uses the fractional part of the number of ticks from January 1, 1970.  To get ticks, you will need to import the time module.  Call the number of ticks by the time.time() function.

Python has no native fractional part.  To extract the fractional part of a number, the following formula is required, where t is any variable:

t = t – math.trunc(t)

The function math.trunc(t) truncates t and returns the integer part.

Keep in mind, to generate n items, use the for loop with the in range(0, n-1)

# Program 006 - Random Number Generation
print("Random number generation")

# import time, use as a seed
import time
t = time.time()
print

# since t is a floating number
# lets import math and use
# math.trunc

import math
t = t - math.trunc(t)

# We are going to use a psuedo-random
# formula to generate n numbers.  n
# will be an integer as range requires.
n = int(input("How many random numbers?"))
for k in range(0,n-1):
     t = (math.pi + t)**5
     t = t - math.trunc(t)
     print(t)

Output (15 numbers generated):

Random number generation
How many random numbers?15
0.8619577822222482
0.5526325838995945
0.045018018769951595
0.5829554424582284
0.7503835409480644
0.9988016770092827
0.770091723446285
0.8387765088751848
0.11795716208871454
0.9494124177641083
0.9088916269388392
0.2717401531838277
0.3329376152682926
0.38460892637095867
(your answers will vary)

Eddie


This blog is property of Edward Shore, 2017.