4 ms·
I assume that the random numbers in bash come from an uniform distribution. Is there a way of getting random numbers from a different distribution with given pa
by torcete 4y ago
I assume that the random numbers in bash come from an uniform distribution. Is there a way of getting random numbers from a different distribution with given parameters?
I can only think of one-liners in R or maybe python.
- zamadatix 4y agoThe standard approach is to take the CDF form of the desired distribution, solve it for equaling some constant, then plug in your uniform value and out comes where on the desired distribution that maps to. The hard part is you either have to pre-solve it or use numerical solving methods and in either case you'd have to write that in Bash.
- pmarreck 4y agofor a normal distribution, chatgpt suggests the box-muller transform and calling out to awk (which is a scripting language that continues to surprise me; it seems underrated?) normal_random() { start=$1 end=$2 range=$(echo "$end - $start" | bc -l) awk -v start=$start -v range=$range -v seed=$RANDOM ' BEGIN { srand(seed); u1 = rand(); u2 = rand(); z0 = sqrt(-2 * log(u1)) * cos(2 * 3.14159265358979323846 * u2); z1 = sqrt(-2 * log(u1)) * sin(2 * 3.14159265358979323846 * u2); random_number = start + (z0 * (range / 6)) + (range / 2); printf("%.0f\n", random_number); }' } In testing it out, they did seem normally-distributed but rerunning it quickly did seem to produce more consecutively duplicate results than would be expected, not sure why that would be (I was using ranges of 0-10 and 0-20, perhaps the probability of normally-distributed consecutive dupes in that range is quite higher?) EDIT: Nope, there's definitely something wrong with this, possibly the rand() call(s)? Can anyone guess? (A real-world example of the perils of relying on chatGPT!) EDIT2: Figured it out. srand with no args seeds to the current second, making any run of this function within the same second produce the same result. Fixing this left as an exercise to the reader EDIT3: I fixed it by seeding it externally via $RANDOM.
- jwilk 4y agoz1 is never used.
- pmarreck 4y agoGood point! chatGPT explained it thusly: "The Box-Muller transform generates two normally distributed random numbers, z0 and z1, using the two uniformly distributed random numbers u1 and u2. However, only z0 is used in the provided function to create the random number within the given range. If you want to additionally supply z1 in the output, you can." It then provides the modified code.
- sureglymop 4y agoAWK is amazing. I recommend reading "The AWK Programming Language", read it as a kid! You can even do network programming with gawk: https://www.gnu.org/software/gawk/manual/html_node/TCP_002fIP-Networking.html https://www.gnu.org/software/gawk/manual/html_node/TCP_002fI...