SDL: Added algorithm comments to SDL_rand_*()

From 38cac043af4ccffe51a408d072f64ee4c30a3c64 Mon Sep 17 00:00:00 2001
From: John Kaniarz <[EMAIL REDACTED]>
Date: Wed, 19 Jun 2024 16:18:00 -0400
Subject: [PATCH] Added algorithm comments to SDL_rand_*()

---
 src/stdlib/SDL_random.c | 15 ++++++++++-----
 test/testnative.c       |  8 ++++----
 2 files changed, 14 insertions(+), 9 deletions(-)

diff --git a/src/stdlib/SDL_random.c b/src/stdlib/SDL_random.c
index dba9e15f06aae..642f3a72fe22f 100644
--- a/src/stdlib/SDL_random.c
+++ b/src/stdlib/SDL_random.c
@@ -36,7 +36,7 @@ void SDL_srand(Uint64 seed)
 
 Uint32 SDL_rand_bits(void)
 {
-    if(!SDL_rand_initialized) {
+    if (!SDL_rand_initialized) {
         SDL_srand(0);
     }
 
@@ -63,12 +63,17 @@ Uint32 SDL_rand_bits(void)
 
 Sint32 SDL_rand_n(Sint32 n)
 {
-	// On 32-bit arch, the compiler will optimize to a single 32-bit multiply
-	Uint64 val = (Uint64)SDL_rand_bits() * n;
-	return (Sint32)(val >> 32);
+    // Algorithm: get 32 bits from SDL_rand_bits() and treat it as a 0.32 bit
+    // fixed point number. Multiply by the 31.0 bit n to get a 31.32 bit
+    // result. Shift right by 32 to get the 31 bit integer that we want.
+
+    // On 32-bit arch, the compiler will optimize to a single 32-bit multiply
+    Uint64 val = (Uint64)SDL_rand_bits() * n;
+    return (Sint32)(val >> 32);
 }
 
 float SDL_rand_float(void)
 {
-	return (SDL_rand_bits() >> (32-24)) * 0x1p-24f;
+    // Note: its using 24 bits because float has 23 bits significand + 1 implicit bit
+    return (SDL_rand_bits() >> (32 - 24)) * 0x1p-24f;
 }
diff --git a/test/testnative.c b/test/testnative.c
index 86e2c113501b5..d5c54e458c693 100644
--- a/test/testnative.c
+++ b/test/testnative.c
@@ -188,15 +188,15 @@ int main(int argc, char *argv[])
         quit(2);
     }
     for (i = 0; i < NUM_SPRITES; ++i) {
-        positions[i].x = (float)(SDL_rand_n((window_w - (int)sprite_w)));
-        positions[i].y = (float)(SDL_rand_n((window_h - (int)sprite_h)));
+        positions[i].x = (float)(SDL_rand_n(window_w - (int)sprite_w));
+        positions[i].y = (float)(SDL_rand_n(window_h - (int)sprite_h));
         positions[i].w = sprite_w;
         positions[i].h = sprite_h;
         velocities[i].x = 0.0f;
         velocities[i].y = 0.0f;
         while (velocities[i].x == 0.f && velocities[i].y == 0.f) {
-            velocities[i].x = (float)((SDL_rand_n((MAX_SPEED * 2 + 1))) - MAX_SPEED);
-            velocities[i].y = (float)((SDL_rand_n((MAX_SPEED * 2 + 1))) - MAX_SPEED);
+            velocities[i].x = (float)(SDL_rand_n(MAX_SPEED * 2 + 1) - MAX_SPEED);
+            velocities[i].y = (float)(SDL_rand_n(MAX_SPEED * 2 + 1) - MAX_SPEED);
         }
     }