How do I generate random numbers using HC-128 in Rust? - random

I would like to generate random numbers using the crate rand_hc. The documentation states:
This implementation uses an output buffer of sixteen u32 words, and uses BlockRng to implement the RngCore methods.
I am very new to rust and do not understand anything in the documentation. How can I just generate a random number in a range 0 to N?

Some minimal code using that random number generator could look like this:
use rand::prelude::*;
fn main() {
let mut rng = rand_hc::Hc128Rng::from_entropy();
println!("{}", rng.gen_range(0, 42));
}
(Playground)
You first need to create an instance of the random number generator, which is done by one of the functions in the SeedableRng trait. I chose from_entropy() above. Once you have an instance of Hc128Rng, you can all functions in the Rng trait to generate random numbers with it.
Note that Hc128Rng does not directly implement the Rng trait. It implements RngCore instead, and there is a blanket implementation implementing Rng for all implementors of RngCore. The split of functionality into two traits allows the RngCore trait to be object safe, but it indeed makes the API somewhat less obvious if you aren't used to it yet.

Related

How to set 256 bit length random number seed

For security, I need to use 256 bits input as the rand seed, but it seems there is no satisfied API or functions, for example, in Golang std library, the seed should be int64, or 64 bits integer.
// Seed uses the provided seed value to initialize the default Source to a
// deterministic state. If Seed is not called, the generator behaves as
// if seeded by Seed(1). Seed values that have the same remainder when
// divided by 2³¹-1 generate the same pseudo-random sequence.
// Seed, unlike the Rand.Seed method, is safe for concurrent use.
func Seed(seed int64) { globalRand.Seed(seed) }
above code is just an inappropriate example, you can ignore it,
crypto/rand is much safer, as we can see in the std library doc.
Is there a way to use 256 bits rand seeds in Golang?
THANKS A LOT !!!
Is there a way to use 256 bits rand seeds in [math/rand] Go[]?
No, for obvious reasons.

What is the difference between rand's Sample and IndependentSample traits?

The rand crate has a Sample trait and an IndependentSample trait.
Obviously, "Independent" is the difference between the two, but what does this mean semantically in the numbers generated? In the non-independent case, how are samples possibly dependent on one another?
The only difference between these two traits is that Sample takes a &mut self whereas IndependentSample takes a &self.
This means that Sample could store a state, but not IndependentSample.
The naming choice is described in IndependentSample documentation:
Since no state is recorded, each sample is (statistically) independent of all others, assuming the Rng used has this property.

Rust GSL library always returns the same number for a random number generator

I am using the rgsl library in Rust that wraps functions from the C GSL math libraries. I was using a random number generator function, but I am always getting the same exact value whenever I generate a new random number. I imagine that the number should vary upon each run of the function. Is there something that I am missing? Do I need to set a new random seed each time or such?
extern crate rgsl;
use rgsl::Rng;
fn main() {
rgsl::RngType::env_setup();
let t = rgsl::rng::default();
let r = Rng::new(&t).unwrap()
let val = rgsl::randist::binomial::binomial(&r, 0.01f64, 1u32);
print!("{}",val);
}
The value I keep getting is 1, which seems really high considering the probability of obtaining a 1 is 0.01.
The documentation for env_setup explains everything you need to know:
This function reads the environment variables GSL_RNG_TYPE and GSL_RNG_SEED and uses their values to set the corresponding library variables gsl_rng_default and gsl_rng_default_seed
If you don’t specify a generator for GSL_RNG_TYPE then gsl_rng_mt19937 is used as the default. The initial value of gsl_rng_default_seed is zero.
(Emphasis mine)
Like all software random number generators, this is really an algorithm that produces pseudo random numbers. The algorithm and the initial seed uniquely identify a sequence of these numbers. Since the seed is always the same, the first (and second, third, ...) number in the sequence will always be the same.
So if I want to generate a new series of random numbers, then I need to change the seed each time. However, if I use the rng to generate a set of random seeds, then I will get the same seeds each time.
That's correct.
Other languages don't seem to have this constraint, meaning that the seed can be manually set if desired, but is otherwise is random.
A classical way to do this is to seed your RNG with the current time. This produces an "acceptable" seed for many cases. You can also get access to true random data from the operating system and use that as a seed or mix it in to produce more random data.
Is there no way to do this in Rust?
This is a very different question. If you just want a random number generator in Rust, use the rand crate. This uses techniques like I described above.
You could even do something crazy like using random values from the rand crate to seed your other random number generator. I just assumed that there is some important reason you are using that crate instead of rand.

Save random state in golang

Is there a way to save the random state in the golang math/rand package?
I would like to serialize it and store it for later use, but the random state is an interface and the concrete struct underneath the interface is unexported (so json.Marshall apparently cannot be used).
As an alternative to saving the rand.Source object, I thought about just saving the underlying int64 seed value. You can set it with rand.Seed, but I don't see a way to obtain the seed value so that it can be retained for later use.
You can make your own random number source which can be marshalled.
One way would be to simply copy the code from http://golang.org/src/math/rand/rng.go and adapt it by adding code that can marshal the state in whatever way you want. That'll give you your own rand.Source that you can use in rand.New(myRandSource) to generate random numbers.
As you already noted, the math/rand package does not give you insight into the current state (seed) of the (pseudo-)random number generator. If you would need this, you would have to implement it on your own (as mentioned by Anonymous).
If you would: Ok, let's say you know that the internal state of the random number generator is equivalent to where a seed value of 1234 would be set. How is this better than if the seed is any other concrete or "random" number?
Here's a tip how to "simulate" access to the seed value of the generator:
Let's say you've already created your Rand object, you've set it up and used it (already generated some random numbers). This Rand object may as well be the default/global of the math/rand package, it doesn't have to be a distinct Rand.
You reach a point where you would like to save the "sate" of the random number generator in order so that later you can repeat the exact pseudo-random sequence from this point. This would need to get the current seed, and later when you want to repeat the sequence from this point, you would just set the stored seed to the Rand object. Problem: the seed you can't access.
But what you can do is set a new seed and then you know that the internal seed is the one you just set! So to simulate a GetSeed() (on the default Rand of the math/rand package):
func GetSeed() int64 {
seed := time.Now().UnixNano() // A new random seed (independent from state)
rand.Seed(seed)
return seed
}
To simulate a GetSeed() or any Rand (not the default one):
func GetSeed2(r rand.Rand) int64 {
seed := time.Now().UnixNano() // A new random seed (independent from state)
r.Seed(seed)
return seed
}
Preserving the "pseudo" part of the randomness
The above proposed GetSeed() uses the current time to "re-seed" the Rand object. This will alter the pseudo-random sequence based on the time it was called at. This may or may not be ok (in most of the times this is not a problem).
But if it is, we can avoid this if we use the Rand object itself to designate the new seed like this (by doing this the new seed will only depend on the current state - the current seed):
func GetSeed() int64 {
seed := rand.Int63() // A new pseudo-random seed: determined by current state/seed
rand.Seed(seed)
return seed
}
func GetSeed2(r rand.Rand) int64 {
seed := r.Int63() // A new pseudo-random seed: determined by current state/seed
r.Seed(seed)
return seed
}
Notes:
The GetSeed() functionality is designed to used occasionally, e.g. when you want to save a game. Normal usage would be to generate thousands of random numbers and call GetSeed() once only.
As Anonymous pointed out, with the current algorithm of the pseudo-random number generator, in some extreme situations (for example you call GetSeed() after each generated random number) this may result in a cycle in the generated random numbers and would return the previously generated sequence of random numbers. The length of the sequence may be around a couple of thousands. Here is an example of this where the length of the sequence is 8034: Repetition Go Playground Example.
But again: this is not a normal usage, GetSeed() is called intentionally after each random number generation; and this only applies if you use Rand itself to generate the new seed. If you re-seed your Rand object with the current time for example, repetition will not occur.

How to implement a pseudo random function

I want to generate a sequence of random numbers that will be used to pick tiles for a "maze". Each maze will have an id and I want to use that id as a seed to a pseudo random function. That way I can generate the same maze over and over given it's maze id. Preferably I do not want to use a built in pseudo random function in a language since I do not have control over the algorithm and it could change from platform to platform. As such, I would like to know:
How should I go about implementing my own pseudo random function?
Is it even feasible to generate platform independent pseudo random numbers?
Yes, it is possible.
Here is an example of such an algorithm (and its use) for noise generation.
Those particular random functions (Noise1, Noise2, Noise3, ..) use input parameters and calculate the pseudo random values from there.
Their output range is from 0.0 to 1.0.
And there are many more out there (Like mentioned in the comments).
UPDATE 2019
Looking back at this answer, a better suited choice would be the below-mentioned mersenne twister. Or you could find any implementation of xorshift.
The Mersenne Twister may be a good pick for this. As you can see from the pseudocode on wikipedia, you can seed the RNG with whatever you prefer to produce identical values for any instance with that seed. In your case, the maze ID or the hash of the maze ID.
If you are using Python, you can use the random module by typing at the beginning,
import random. Then, to use it, you type-
var = random.randint(1000, 9999)
This gives the var a 4 digit number that can be used for its id
If you are using another language, there is likely a similar module

Resources