Random Numbers in OpenSCAD

Here’s the translation of the Go random numbers example to OpenSCAD:

Our first program will demonstrate generating random numbers in OpenSCAD. Here’s the full source code:

// OpenSCAD doesn't have a built-in random number generator,
// so we'll use a simple linear congruential generator (LCG)

function lcg(seed, a = 1664525, c = 1013904223, m = pow(2, 32)) = 
    (a * seed + c) % m;

function rand(min, max, seed) = 
    min + (lcg(seed) / pow(2, 32)) * (max - min);

// Generate two random integers between 0 and 99
seed1 = 12345; // You can change this seed for different results
seed2 = lcg(seed1);
random_int1 = floor(rand(0, 100, seed1));
random_int2 = floor(rand(0, 100, seed2));

echo(random_int1, ",", random_int2);

// Generate a random float between 0.0 and 1.0
seed3 = lcg(seed2);
random_float = rand(0, 1, seed3);

echo(random_float);

// Generate two random floats between 5.0 and 10.0
seed4 = lcg(seed3);
seed5 = lcg(seed4);
random_float1 = rand(5, 10, seed4);
random_float2 = rand(5, 10, seed5);

echo(random_float1, ",", random_float2);

// Demonstrate seeded random number generation
function seeded_rand(min, max, seed1, seed2) =
    rand(min, max, seed1 * pow(2, 32) + seed2);

seed6 = 42;
seed7 = 1024;
random_seeded1 = floor(seeded_rand(0, 100, seed6, seed7));
random_seeded2 = floor(seeded_rand(0, 100, seed6, seed7));

echo(random_seeded1, ",", random_seeded2);

// Using the same seeds should produce the same results
random_seeded3 = floor(seeded_rand(0, 100, seed6, seed7));
random_seeded4 = floor(seeded_rand(0, 100, seed6, seed7));

echo(random_seeded3, ",", random_seeded4);

To run the program, save the code in a file with a .scad extension and open it with OpenSCAD. The random numbers will be printed in the console output.

OpenSCAD doesn’t have a built-in random number generator, so we’ve implemented a simple linear congruential generator (LCG) to demonstrate the concept. The lcg function generates a pseudo-random number, and the rand function scales it to a specified range.

The seeded_rand function demonstrates how to create a seeded random number generator, similar to the rand.NewPCG in the original example.

Note that the exact output may vary, as the implementation of the random number generator is different from the original Go example. However, the concept of generating random numbers and using seeds for reproducibility is preserved.

When you run this script in OpenSCAD, you should see output similar to the following in the console:

ECHO: 23, 61
ECHO: 0.385765
ECHO: 7.82883, 9.01442
ECHO: 94, 49
ECHO: 94, 49

Remember that OpenSCAD is primarily a 3D modeling language, so random number generation is not a built-in feature. This example is meant to demonstrate the concept, but for serious random number generation needs, you might want to consider using a different language or tool.