Skip to content

Commit 38cac04

Browse files
JKaniarzslouken
authored andcommitted
Added algorithm comments to SDL_rand_*()
1 parent 8f29f8c commit 38cac04

File tree

2 files changed

+14
-9
lines changed

2 files changed

+14
-9
lines changed

src/stdlib/SDL_random.c

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ void SDL_srand(Uint64 seed)
3636

3737
Uint32 SDL_rand_bits(void)
3838
{
39-
if(!SDL_rand_initialized) {
39+
if (!SDL_rand_initialized) {
4040
SDL_srand(0);
4141
}
4242

@@ -63,12 +63,17 @@ Uint32 SDL_rand_bits(void)
6363

6464
Sint32 SDL_rand_n(Sint32 n)
6565
{
66-
// On 32-bit arch, the compiler will optimize to a single 32-bit multiply
67-
Uint64 val = (Uint64)SDL_rand_bits() * n;
68-
return (Sint32)(val >> 32);
66+
// Algorithm: get 32 bits from SDL_rand_bits() and treat it as a 0.32 bit
67+
// fixed point number. Multiply by the 31.0 bit n to get a 31.32 bit
68+
// result. Shift right by 32 to get the 31 bit integer that we want.
69+
70+
// On 32-bit arch, the compiler will optimize to a single 32-bit multiply
71+
Uint64 val = (Uint64)SDL_rand_bits() * n;
72+
return (Sint32)(val >> 32);
6973
}
7074

7175
float SDL_rand_float(void)
7276
{
73-
return (SDL_rand_bits() >> (32-24)) * 0x1p-24f;
77+
// Note: its using 24 bits because float has 23 bits significand + 1 implicit bit
78+
return (SDL_rand_bits() >> (32 - 24)) * 0x1p-24f;
7479
}

test/testnative.c

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -188,15 +188,15 @@ int main(int argc, char *argv[])
188188
quit(2);
189189
}
190190
for (i = 0; i < NUM_SPRITES; ++i) {
191-
positions[i].x = (float)(SDL_rand_n((window_w - (int)sprite_w)));
192-
positions[i].y = (float)(SDL_rand_n((window_h - (int)sprite_h)));
191+
positions[i].x = (float)(SDL_rand_n(window_w - (int)sprite_w));
192+
positions[i].y = (float)(SDL_rand_n(window_h - (int)sprite_h));
193193
positions[i].w = sprite_w;
194194
positions[i].h = sprite_h;
195195
velocities[i].x = 0.0f;
196196
velocities[i].y = 0.0f;
197197
while (velocities[i].x == 0.f && velocities[i].y == 0.f) {
198-
velocities[i].x = (float)((SDL_rand_n((MAX_SPEED * 2 + 1))) - MAX_SPEED);
199-
velocities[i].y = (float)((SDL_rand_n((MAX_SPEED * 2 + 1))) - MAX_SPEED);
198+
velocities[i].x = (float)(SDL_rand_n(MAX_SPEED * 2 + 1) - MAX_SPEED);
199+
velocities[i].y = (float)(SDL_rand_n(MAX_SPEED * 2 + 1) - MAX_SPEED);
200200
}
201201
}
202202

0 commit comments

Comments
 (0)