Rand functions which return a random value

The various rand functions in Mojo’s current Random library currently all take a region of memory via an unsafe pointer as a parameter and fills it with random values, and thus are memory unsafe.

However, in other systems level programming languages such as C, C++, and Rust, the rand functions in the standard library or the rand crate are functions which return a single random value. Will Mojo implement similar rand functions as those in the other languages? Such rand functions will be memory safe since they do not involve unsafe pointers.

Looking at the source code for Mojo’s random library:

the random functions there seem to be wrappers of functions from the KGen compiler for Python, which themselves are wrappers of Fortran’s random functions.

That is, unlike C/C++/Rust there is currently no native random library implemented solely in the Mojo language.

This is a good question. The random module is one of the older ones and could use some modernization. We should at least probably take a Span instead of an UnsafePointer and length.

functions which return a single random value

If you look in that same module you linked, you can see the methods:

fn random_float64(min: Float64 = 0, max: Float64 = 1) -> Float64:
fn random_si64(min: Int64, max: Int64) -> Int64:
fn random_ui64(min: UInt64, max: UInt64) -> UInt64:

which all return a single value. If you want to truncate them, you can then cast the result, e.g:

UInt32(random_ui64(0, 5))

For me, all these functions don’t work as the linking seems broken. I get something like Unresolved extern function 'KGEN_CompilerRT_RandomSInt64

This doesn’t repro on my machine. Can you give us more information about your setup / hardware / operating system?

Also note you should be calling random.seed yourself otherwise you will always be using the default seed of 0.

Hey Lukas, Apologies for the confusion! I found out that it works just fine on our cluster, however when I use slurm, I get the error Unresolved extern function 'KGEN_CompilerRT_RandomSInt64 . I put #!/bin/bash -l at the start of my shell script that I submit to slurm, but that also dosn’t seem to work. Any pointers are welcome!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.