0

in the following code:

float sfrand( int *seed )
{
    float res;

    seed[0] *= 16807;

    *((unsigned int *) &res) = ( ((unsigned int)seed[0])>>9 ) | 0x40000000;

    return( res-3.0f );
}

source: http://iquilezles.org/www/articles/sfrand/sfrand.htm

phuclv
  • 37,963
  • 15
  • 156
  • 475
DrGo
  • 411
  • 3
  • 7
  • 1
    that's one of the worst RNGs ever: [Rand() % 14 only generates the values 6 or 13](https://stackoverflow.com/a/20267526/995714), [Why does rand() % 7 always return 0?](https://stackoverflow.com/q/7866754/995714) – phuclv Mar 04 '19 at 23:45

3 Answers3

1

seed[0] is same as *seed, that is the first integer (possibly the only one, if it doesn't point to an array) pointed to by seed pointer.

*= operator is "assignment by product" operator,

seed[0] *= 16807; is same as

*seed = *seed * 16807;, which is what the line you ask about does.

The whole function is a simple algorithm to generate pseudo-random numbers, it seems. The purpose of modifying the seed is, that next call will produce a different pseudo-random number.

hyde
  • 60,639
  • 21
  • 115
  • 176
  • Thanks hyde. seed[0]==*seed is what I was asking about. Are you saying that in c a pointer to an int can be also a pointer to an array of ints? In this case, I do not see much point of passing an array of int as a seed. So why the author did not simply use *seed *= 16807? Am I missing something? Thanks again – DrGo Mar 03 '19 at 23:01
  • 1
    @SSMM Perhaps there are other functions (or just an external API) which requires `seed` to be an array, so all the functions use array index notation even if they only use the first integer (usually the random seed is larger than single integer, to make it longer before the pseudo-random number sequence starts repeating itself). Perhaps the programmer just personally preferred this syntax. It is a bit unusual to use `ptr[0]` if it doesn't point to an array. But you're not really missing anything here, as far as I can see, there's no hidden meaning. – hyde Mar 04 '19 at 07:08
0

The seed[0] *= 16807; line is just a shortcut for seed[0] = seed[0] * 16807;

Here's a list of similar constructs: https://www.programiz.com/c-programming/c-operators

user4487338
  • 78
  • 1
  • 6
0

*= is a composite operator for multiplication. In this operator, the result that left operand multiplies to right operand will be stored with left operand. So in this statement seed[0] *= 1680;, left operand is seed[0], right operand is 1680. After this statement is executed, seed[0] will be equal to seed[0] * 1680. The is a similar statement for it:

 seed[0] = seed[0] * 1680;

We have some composite operators: +=, -=,/=, ... that are working in the same behavior.

Loc Tran
  • 1,170
  • 7
  • 15