Search code examples
randompostscript

Generate random number in interval in PostScript


I am struggling to find a way to generate a random number within a given interval in PostScript.

Basically PostScript has three functions to help you generate (pseudo-)random numbers. Those are rand, srand and rrand.

The later two are for passing a seed to the number generator to be able to reproduce specific results. At least that´s what I understood they are for. Anyway they don´t seem suitable for my case.

So rand seems to be the only function I can use to generate a random number, but...

rand returns a random integer in the range 0 to 231 − 1
(From the PostScript Language Reference, page 637 (651 in the PDF))

This is far beyond the the interval I´m looking for. I am more interested in values up to small thousands, maybe 10.000 or something like that and small float values, up to 100, all with the lower limit of 0.

I thought I could just narrow my numbers down by simple divisions and extracting the root but that tends to give me unusable small values in quite a lot cases. I am wondering if there are robust ways to either shrink a large number down to what I need or, I´d prefer that, only generate numbers in the desired interval.

Besides: while-loops are not possible in PostScript, otherwise I´d have written a function to generate numbers until they fit in my interval.

Any hints on what to look for breaking numbers down into my interval?


Solution

  • mod is often good enough and it's fast. But you may get a more uniform distribution by using floating-point ops.

    rand 16#7fffffff div 100 mul cvi
    

    This is because mod discards the upper bits of the input. And the PRNG is usually trying to randomize over all the bits. By scaling down then up, they all contribute something in the way of rounding effects.