Tip #3 - Quick and dirty random numbers

Sometimes you just need a pseudo-random number. Useful for sampling vertices from a graph or if you write data generators in GSQL.

So, these days I have a UDF for this, but sometimes you don’t have that available, and you need a random number. For this I have a small generator. These aren’t particularly good random numbers, but for basic work they seem to be okay.
Here is the routine. Note you feed it with a floating point number between 0 and 1. No doubt there are better generators, but for that I use a UDF.

Here it is:

  CREATE QUERY  myRand(FLOAT prev_rand) FOR GRAPH MyGraph RETURNS (FLOAT) {
  // Cliff's number generator
  // This is NOT cryptographically secure
  // As it has no entropy, and is entirely predictable

   FLOAT rand_out;
      
      IF  prev_rand<0.000001 THEN  // zero test without a warning
        rand_out = 0.1; // Cliff's standard starting value
      ELSE
        rand_out=prev_rand;
      END;
      
      rand_out = 100*log(rand_out);
      rand_out = abs(rand_out);
      rand_out = rand_out - floor(rand_out);
      
       PRINT rand_out; // only prints when run standalone i.e. debug
      
      RETURN rand_out;
    }
2 Likes