Sionae
Sionae

Reputation: 23

Create a "random" number between range without any module except time

I would like to create myself a "random" number generator of integers between 2 edges. Moreover, I would like to create the same thing but with float numbers between two edges (like the random.random but of the range I want).

Time is required for me for timestamps.

I am currently learning the way random numbers are generated (I am using this way with timestamp as a start):

a = int
b = int
m = int
number = time.mktime (time.localtime ())

for x in range (0, m):
    number = (a*number + c) % m
    print (number)

(int can be any integer number. There are multiple ways to optimize the returned values (to long to explain here))

This is the way I've learnt to have "random" integers. I am currently searching for a way to solve the problem above using this way (if possible). Any ideas?

Upvotes: 0

Views: 637

Answers (1)

bigblind
bigblind

Reputation: 12867

Given that you're always taking your number modulo m, m is the maximum value of the result. Also, finding a random number between min and max is the same as finding a random number between 0 and max - min, and adding min to that.

def rand_range(min, max, a, b, n):
    m = max - min
    number = time.mktime (time.localtime ())

    for x in range (0, m):
        number = (a*number + b) % m

    return number + min

To get a floating point number out of this, you can use the function above to define:

def rand_range_float(min, max, density, a, b, n):
    rand_int = rand_range(0, density, a, b, n)
    return min + (float(rand_int)/density)*(max-min)

In this function, density specifies how many possible floating point values you want. For example, if you'd call rand_range_float(0, 1, 2, a, b, c), the function could return 2 possible values; 0.0 or 0.5

Upvotes: 1

Related Questions