Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple random number generator that can generate nth number in series in O(1) time

I do not intend to use this for security purposes or statistical analysis. I need to create a simple random number generator for use in my computer graphics application. I don't want to use the term "random number generator", since people think in very strict terms about it, but I can't think of any other word to describe it.

  • it has to be fast.
  • it must be repeatable, given a particular seed. Eg: If seed = x, then the series a,b,c,d,e,f..... should happen every time I use the seed x.

Most importantly, I need to be able to compute the nth term in the series in constant time.

It seems, that I cannot achieve this with rand_r or srand(), since these need are state dependent, and I may need to compute the nth in some unknown order.

I've looked at Linear Feedback Shift registers, but these are state dependent too.

So far I have this:

int rand = (n * prime1 + seed) % prime2

n = used to indicate the index of the term in the sequence. Eg: For first term, n ==1

prime1 and prime2 are prime numbers where prime1 > prime2

seed = some number which allows one to use the same function to produce a different series depending on the seed, but the same series for a given seed.

I can't tell how good or bad this is, since I haven't used it enough, but it would be great if people with more experience in this can point out the problems with this, or help me improve it..

EDIT - I don't care if it is predictable. I'm just trying to creating some randomness in my computer graphics.

like image 783
Rahul Iyer Avatar asked Feb 22 '14 04:02

Rahul Iyer


1 Answers

Use a cryptographic block cipher in CTR mode. The Nth output is just encrypt(N). Not only does this give you the desired properties (O(1) computation of the Nth output); it also has strong non-predictability properties.

like image 118
R.. GitHub STOP HELPING ICE Avatar answered Nov 15 '22 23:11

R.. GitHub STOP HELPING ICE