Maybe there is some math wizard around here who can provide some ideas.
I need a ‘controlled random’ number system using some probability scale.
I already have my own basic rnd.next_inclusive(min, max) for any type of int.
A few examples:
const r = rnd.next(1, 4); // 1 is very probable and 4 is very rare.
const r = rnd.next(5, 100); // 5 is very rare, in between is common, 100 is very rare.
Would it be possibe to add be 1 smart argument to rnd.next() controlling these probabilities?
I had a short look at the interesting:
but I don’t know all these distributions we see in there.
I’m not sure I fully understand your problem statement, but it seems to me like you’re looking to generate numbers within a range, such that number closers to the midpoint of the interval are more likely, in which case you could generate numbers using, for example, a binomial distribution (note that the wikipedia page has some material on how to sample from that distribution computationally). More generally, you may want to look for distributions which mass function is ‘bumpy’ in the middle.
One way to sample abitrary random numer distributions is the metropolis hastings monte carlo.
I am away from the keyboard atm. But when i get home i can provide you with some code examples if you want.
are you using this function for implementing yours intRangeAtMost?
yes. i wrote my own, because it needs to stay the same for always 
The Metropolis-Hastings-Monte-Carlo maps a uniform distribution of random numbers from the interval [0:1] to an arbitrary probability distribution W(r).
It works by having a previous random number r_old ([-inf,inf]) and proposing a new random number r_new ([-inf,inf]). The new random number is accepted with the probability min(1, W(r_new)/W(r_old)).
That basically means you compute the probability distribution for r_old and r_new.
If W(r_new)/W(r_old) is larger than 1 the new value is automatically accepted. If not it is compared to a third random number r_comp ([0,1]). If the quotient is larger or equal to r_comp, r_new is accepted.
The distribution of r_new follows the probability density of your W(r) function.
This algorithm is one of the most flexible ways to produce arbitrary random number distributions of your liking.
I wrote some terrible code for you that should make the process clear, and let you adapt it to your problem:
Example Code
const std = @import("std");
const Io = std.Io;
pub fn my_prob_dens(a: f32) f32 {
if (a <= -3.0) {
return 0;
} else if (a <= -1.0) {
return 1.0;
} else if (a <= 3.0) {
return 2.0;
} else if (a <= 5.0) {
return 4.0;
} else {
return 0;
}
}
var last_rng: f32 = 0.0;
var prng: std.Random.DefaultPrng = undefined;
pub fn metropolisHastingsMC() f32 {
const step_width: f32 = 1.0;
const rand = prng.random();
const proposed_rng = last_rng + step_width * (rand.float(f32) - 0.5);
var metropolis: f32 = my_prob_dens(proposed_rng) / my_prob_dens(last_rng);
metropolis = if (metropolis > 1.0) 1.0 else metropolis;
if (metropolis >= rand.float(f32)) {
last_rng = proposed_rng;
}
return last_rng;
}
pub fn main(init: std.process.Init) !void {
const io = init.io;
var stdout_buffer: [1024]u8 = undefined;
var stdout_file_writer: Io.File.Writer = .init(.stdout(), io, &stdout_buffer);
const stdout_writer = &stdout_file_writer.interface;
var seed_bytes: [8]u8 = undefined;
std.Io.random(io, &seed_bytes);
const seed: u64 = std.mem.readInt(u64, seed_bytes[0..8], .little);
prng = std.Random.DefaultPrng.init(seed);
const n = 10000000;
for (0..n) |_| {
const r = metropolisHastingsMC();
try stdout_writer.print("{d:1.0}\n", .{@floor(r)});
}
try stdout_writer.flush(); // Don't forget to flush!
}
If you take the output and process it with zig build run | sort -nk 1 | uniq -c > data and then plot it, you will get the same distribution that you defined in my_prob_dens
The algorithm has some serious drawbacks.
- The efficiency strongly depends on the step_width, with which you generate new random numbers from the old ones. Too small, and your random numbers are highly correlated, thus useless for anything serious. Too big, and they are probably always rejected, thus you will always get the same value.
- Depending on your probability distribution you might get trapped in an interval, inable to escape to other parts of the distribution function.
- You need to equilibrate it properly. Since you select a hard coded “first” random number, you have to run a few samples and throw them away, to get in a probable state.
- In order to get uncorrelated random numbers, you might want to sample the algorithm several times and only keep the last number. This can be quite slow.
- The speed strongly depends on the evaluation of your probability distribution. For example this algorithm is often used to generate Boltzmann distributed Molecular structures, where the evaluation of the probability density can take minutes to hours for one Step!
If you have any questions, I will do my very best to answer them.
I hope this helps.
Edit: No need to normalize your distribution function. It happens automatically.
I don’t have any fancy algorithm name to point to, but it sounds like the classic problem with creating loot tables in a game, where you have different tiers of loot (e.g. common, rare, legendary) to choose from.
Is it something like that? if so, there is tried and true way AAA game companies often accomplish this that I am familiar with, which is quite simple to implement. I actually recently saw a Blizzard employee doing a video of how he implemented it for World of Warcraft, and I am sure I could find it again without much trouble.
EDIT: I found it, hopefully your problem is similar enough where this can be helpful.
If you want to select elements from a finite list, each with its own probability, there is of course also an algorithm for it. I also don’t know the name, but I know where I programmed it before. If you want I can go hunting for the code.
I wrote some RNG functions (that I basically never used) yonks ago with the goal of solving this very problem.
Here are some excerpts:
/// You might think the exponent parameter is used on the result, but it's actually
/// used to bias the RNG towards the start or end of the range.
/// If you call this function with an exponent of 2, we square the 0-1 random float that we
/// generate - thus biasing it towards the start of the range.
/// Conversely, if you call this function with an exponent of 1/2 (0.5), it will bias it towards
/// the end of the range.
/// If you want no bias, simply supply an exponent of 1.
/// Negative exponents aren't checked for, and they will cause pretty wacky, out-of-range results. Beware!
pub fn range(prng: std.Random, start: f32, end: f32, exponent: f32) f32 {
const rng = prng.float(f32);
return start + (end - start) * std.math.pow(f32, rng, exponent);
}
/// This function is similar to range(), but the exponent is used to control the slope of the bell curve
/// instead of biasing the overall result.
/// More specifically, an exponent from 0 to 1 will bias the bell curve AWAY from the centre, so it'll have
/// more extreme results on both sides of the range, and fewer in the centre.
/// An exponent above 1 will bias the bell curve towards the centre.
pub fn range_bell_curve(prng: std.Random, start: f32, end: f32, exponent: f32) f32 {
const rng = prng.float(f32);
const sign = prng.boolean();
const rng_adjusted = 0.5 * std.math.pow(f32, rng, exponent);
const curve_factor = if(sign) 0.5 - rng_adjusted else 0.5 + rng_adjusted;
return start + (end - start) * curve_factor;
}
(It seems that I didn’t know about std.math.lerp() back then.)