crandomsrand

C custom random function


I would like to create a fast lightweight function in C language that returns a pseudo random unsigned char. The challenging part for me (an ANSI C programmer)is that I cannot use the <stdio.h> or any other ready made functions. Any suggestions..?

by "fast" I meant: avoid unnecessary code (Eg if statements, loops etc) by "lightweight" I meant: use as less variables as possible

thanks


Solution

  • Use a Linear Congruential Generator

    E.g.

    uint32_t state = 777;
    
    char myRand()
    {
       state = state * 1664525 + 1013904223;
       return state >> 24;
    }
    

    Note that myRand returns the high bits, they are more pseudo-random than the low bits.

    Linear Congruence Generators were introduced by D. H. Lehmer in 1949 (see Proc. 2nd Symp. on Large-Scale Digital Calculating Machinery (Cambridge, Mass.: Harvard University Press, 1951), 141-146). The concrete numeric constants I gave seem to originate from Press, William H.; et al. (1992). Numerical Recipes in Fortran 77: The Art of Scientific Computing (2nd ed.). ISBN 978-0-521-43064-7.