Equivalent to Math.random()


Is there something equivalent to Math.random() - JavaScript | MDN or I have to implement my own?

This conversation likely interests you - Secure lottery function / Random Number Generation

Random module is here - Random :: Internet Computer


thank you! It seems that I will have to write something myself then.

I gave it a go here xorshift128plus.mo · GitHub
Seems to be generating pseudo random numbers but since I’m new Motoko learner I’m pretty sure it can be written better.

1 Like

My implementation takes around 15s to return… Generating blobs is expensive and also I need to learn more about how to handle state

The latest version takes ~3s but still, it is too much. It seems that since I mutate the state it needs consensus…

1 Like

Just a heads up ~3 second consensus is built into the local dev environment so developers won’t be surprised when they deploy to the mainnet. But you’re spot on - All update calls require consensus. Query calls do not.


ah, I see. ty you for the clarification @Steve

What’s left now to replicate Math.random is to convert the returned integer to a Float between 0 and 1…
I’m trying to figure it out from v8/math-random.cc at dc712da548c7fb433caed56af9a021d964952728 · v8/v8 · GitHub

Hey @chchrist, here is a thought!

Since Nat8 can store the values 0…255, all you have to do is divide the random number by highest possible number:

var myRandom : Nat8 = 123;
let mappedRandom : Float = Float.fromInt(myRandom) / Float.fromInt(255);

A better way might be to use the Random::rangeFrom function:

  /// Distributes outcomes in the numeric range [0 .. 2^p - 1].
  /// Seed blob must contain at least ((p+7) / 8) bytes.

So you could do something like

let random = Random.rangeFrom(32, someBlob)
// between 0..4294967295
let max : Float = 4294967295;
let newRandom = Float.fromInt(random) / max;

ty @Hazel! As Einstein once said " The definition of genius is taking the complex and making it simple."

Now I need to find out why I’m getting this error…

The Replica returned an error: code 5, message: "Canister rrkah-fqaaa-aaaaa-aaaaq-cai trapped explicitly: losing precision"

:thinking: now I didn’t expect that! I guess that makes sense though - I’ll need to think a bit on a better mapping function.

Are you using fixed-with numbers (e.g. Int8)? “losing precision” sounds like the error message when a lossy conversion actually loses data.