Advertisement
Kitomas

deterministic float prng using an xorshift

May 12th, 2023 (edited)
1,047
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.91 KB | Source Code | 0 0
  1. //32-bit xorshift lfsr
  2. int lfsr32(){
  3.   static int last=0xfeedbac;//k (starting number must be non-zero)
  4.   int current=last ^ (last<<13);
  5.   current^=last>>17;
  6.   current^=last<< 5;
  7.   last=current;
  8.   return last;
  9. }
  10. //should return a float between 0.0 -> 1.0
  11. float lfsr_float(){
  12.   union { int i; float f; } value;
  13.   //basically, all bits are random, except the exponent bits always make 2^0
  14.    //(this should = -1.99...->-1.0 OR 1.0->1.99...)
  15.   value.i=(lfsr32()&0x807fffff) | 0x3f800000;
  16.   //1.0 if original value.f = -1.0 (as i don't think 1.0 could occur otherwise)
  17.   if(value.i==0xbf800000) return 1.0f; //1.0
  18.   else if(value.f>=0.0f) return (value.f-1)*0.5f; //0.0 -> 0.499...
  19.   else /*if(value.f<0.0f)*/ return 0.5f-(value.f+1)*0.5f; //5.0 -> 0.99...
  20. }
  21. //should do the same thing with a larger range, but uses a division
  22. static inline float lfsr_float2(){
  23.   return (float)((unsigned)lfsr32())/0xffffffff;
  24. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement