Post Reply 
Hp Algorithm to create random numbers
08-21-2024, 05:43 PM
Post: #9
RE: Hp Algorithm to create random numbers
(08-19-2024 10:23 PM)Gil Wrote:  And what is the algorithm/function to get the first RANDom number when entering x RDZ RAND (x a real number)?

RAND is no different in this scenario than previously described, so what you're really asking is "how does RDZ compute a seed?", which turns out to be difficult to explain without some Saturn assembly knowledge.

The Saturn code for RDZ is concise and efficient, but it doesn't map well to higher-level mathematical translation because it is heavily dependent on the internal representation of reals and "bit-twiddling" steps that are much easier to do in Saturn code than they are with traditional numeric calculations.

That said, I've attempted to create a User RPL version of RDZ that returns an exact integer seed for the given basis, leaving it on the stack instead of storing it internally. It treats an input of 0 in the same way that RDZ does, ie. using the system clock for the seed basis. This code requires a 49g/49g+/50g due to its use of exact integers. The use of reals and integers is important here, so the program should be transferred while the destination calculator is in exact mode.

Code:
RDZU
\<<
  @ if given 0, use the low-order 20 bits of the system clock instead
  IF
    DUP NOT
  THEN
    TICKS NIP
    RCWS 20 STWS
    SWAP B\->R SWAP
    STWS
  END

  @ we need a non-negative real number for the seed basis
  I\->R ABS

  @ separate the mantissa and exponent fields as integers
  DUP MANT 1E14 * R\->I
  SWAP XPON 1000. + 1000. MOD R\->I

  @ denormalize
  DO
    1 +
    CASE
      OVER NOT THEN 1. END
      DUP 2 * 1000 IDIV2 SWAP NOT THEN DROP 1. END
      NOT THEN 1. END
      SWAP 10 IQUOT SWAP
      0.
    END
  UNTIL
  END

  @ replace exponent field after left-shift/increment
  10 * 1 + 1000 MOD
  SWAP 1000 IQUOT 1000 *
  +
\>>

Note that the resulting seed should be interpreted as having leading 0s if its length is less than 15 digits. So a result of 999001 should be interpreted as 000000000999001 when stored internally.

Some examples

1E-13 RDZU => 1
12345. RDZU => 123450000000051
9.87654321098E295 RDZU => 987654321098961
0.000000000999 RDZU => 999001

Full RAND check

12345 RDZU        => 123450000000051
2851130928467 *   => 351972113119396557677351817
10 15 ^ MOD       => 396557677351817
...so RAND should be 0.396557677351

12345 RDZ RAND    => 0.396557677351



9.99E-10 RDZU     => 999001
2851130928467 *   => 2848282648669461467
10 15 ^ MOD       => 282648669461467
...so RAND should be 0.282648669461

9.99E-10 RDZ RAND => 0.282648669461
Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
RE: Hp Algorithm to create random numbers - DavidM - 08-21-2024 05:43 PM



User(s) browsing this thread: 14 Guest(s)