Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C custom random function

Tags:

c

random

srand

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

like image 208
nonouco Avatar asked Dec 10 '22 07:12

nonouco


1 Answers

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.

like image 67
Peter G. Avatar answered Dec 24 '22 06:12

Peter G.