394 points · by Alifatisk · 3y ago · 146 comments
It's sort of like asking, "What would happen if I multiply a bunch of numbers together that are guaranteed to be less than 1 (and even much less than 1 much of the time)?"
random(x) = random()*x
then you can easily see that random(random(random())) = random()*random()*random()
The resulting distribution is not equal to random()^3, because e.g. the probability that all 3 random calls give you a number <0.5 is only 0.125.One of the earliest and most famous examples is Elite [2]:
> The Elite universe contains eight galaxies, each with 256 planets to explore. Due to the limited capabilities of 8-bit computers, these worlds are procedurally generated. A single seed number is run through a fixed algorithm the appropriate number of times and creates a sequence of numbers determining each planet's complete composition (position in the galaxy, prices of commodities, and name and local details; text strings are chosen numerically from a lookup table and assembled to produce unique descriptions, such as a planet with "carnivorous arts graduates").
For more details and screenshots see this great blog post: https://evoniuk.github.io/posts/pitfall.html
The proc gen is also consistent and persistent, based on some initial seed value decided upon at some point in the game's genesis; A CMDR who jumps their ship to some star system never visited before has that star system generated by their game client according to its algorithm - all the system bodies and their types and classes and whatever's on any planets, if anything.
Another CMDR who subsequently visits it will see the same thing the original CMDR saw.
It's a thing of beauty.
Which implementation of random is processing using? There's a lot of random() implementations that aren't suitable for crypto (like JavaScript and Java).
1. https://docs.oracle.com/javase/8/docs/api/java/security/Secu...
2. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
1. So what’s happening here?
Conceptually, this goes around the circle in steps of 1 degree, say, and for each ray plots a point at a distance from the circumference given by random(), or random(random()), etc.
So, conceptually,
For phi = 1..360
r = 1 - random() // etc.
x = r*cos(phi)
y = r*sin(phi)
(It might choose phi randomly uniformly instead, doesn’t matter)2. What’s random(random())?
As explained in detail elsewhere, since the argument specifies the upper limit of the uniform, it equals random()*random() (ie the product of two independent uniform 0-1 random variables).
3. Why is the first image denser in the center, and the second uniform?
Imagine cutting the disk into 100 rings of equal (small) thickness. The area of a ring is approximately thickness times circumference of the ring, in other words, proportional to the distance from the center.
If we put the same number of points into each ring, the rings near the center (with less area) will have more points per area than the rings at the outside, thus appear darker.
If, however, we put more points into the outer rings, and in particular if we make the number of points proportional to the distance from the center, then we will get a more uniform picture.
4. Why 1-random(), rather than random()?
With the latter, we’d just get a series of disks with the bulk of the points concentrated in the centre, increasingly so. Less interesting than what’s here.
So, here's a derivation: if rand(x) returns uniformly a real in [0,x) or equivalently for expected value, in [0,x], then here are the first few iteration expected values from which you can see the general answer. 1 term
E(r) = (1/1) * Integral_0^1 x_0 dx_0 = (x_0^2/2) from 0 to 1 = 1/2
2 terms E(r(r)) = (1/1) * Int_0^1 (1/x_0) Int_0^x_0 x_1 dx_1 dx_0 = 1/4
3 terms: E(r(r(r))) = (1/1) * Int_0^1 (1/x_0) Int_0^x_0 (1/x_1) Int_0^x_1 x_2 dx_2 dx_1 dx_0 = 1/8
And so on. The nth term is exactly (1/2)^n The resulting distribution is not equal to random()^3, because e.g. the probability that all 3 random calls give you a number <0.5 is only 0.125.
https://news.ycombinator.com/item?id=35954931Any thoughts? Am I mixing up two unrelated things?
You can prove the EVs for yourself, but an intuitive way to think about why the EV of the first is twice as much as the second scenario is to consider their probability density functions. When you cube a single random variable, the resulting PDF is skewed towards lower values, but not as dramatically as when you multiply three separate random variables together.
Let's clarify what this means, that's probably the confusion. Here's python code
from random import random
x = random()
z = x*3
That's the random()^3 term. But let's try to differentiate this
a,b,c = random(), random(), random()
z = a * b * c
You may notice that the z's don't match in these cases. The key difference is that in the exponent version we draw a single random variable (remember it is >0 and <1). Then we take this value and multiply it by itself 3 times (cube). This corresponds to rolling a dice once and then multiplying the value by itself 3 times (x*x*x). But in the other case we have 3 independent random variables. This is like rolling the dice 3 times and multiplying the 3 different values. Clearly the possibilities of achieving a specific number are going to be different in these situations. What I suggest doing is plotting a histogram of this data (10k samples with 1k bins will be sufficient). Make 3 plots (preferably using subplot). I went ahead and did this for you[0]!
== Worked out ==
Let's actually simplify this a bit[1] and work it out by hand: we'll look at r^2 vs r*r (where r is an independent random uniform variable). We'll look at an upper bound and the middle.
So in r^2 90% of our r's will be under 0.9, with 9% of values in r^2 being <0.81. Now the middle case, r=0.5. Half our values are above 0.25, and half are <0.25. From this we can see 3 bins: <0.25/0.25 - 0.81/>0.81. 50% of our data is <0.25, 40% is between 0.25 and 0.81, and 10% is >0.81. We can tell from these three bins that our data is pushed towards 0 and we have a long tail.
Now let's look at the r*r case. We'll need to write out more possibilities because we have more cases. 0.9*0.9=0.81, 0.5*0.9=0.9*0.5=0.45, 0.5*0.5=0.25. You see we've added an extra bin because the r's don't have to be the same (lucky for symmetry though). Our bins are <0.25/0.25-0.45/0.45-0.81/>0.81. This now corresponds to 25% of the data, 20% of the data, 36% of the data, and 19%. If we look at these bins, we can see that this is flatter. In the r^2 case we had 50% of our data under 0.25 but in the r*r case we only have 25%! Similarly in the r^2 case we had 10% of our data >0.81 compared to 19%! So we should expect a similar shape but flatter.
I hope this helps.
== Quiz to test your understanding: ==
We're going to make a bet and I'm giving you two options. In the first option I'll allow you to roll a dice, take the value, and cube it. In the second case I'll allow you to roll 3 dice and multiply all values. You win if your result is >63. Which option do you choose? What if you win when the result is <8? (I'm sure someone will post an answer)
[0] https://i.imgur.com/gQ5uqED.png
[1] I started writing out the full case but it got long winded so I deleted. I can redo if needed.
It's interesting that the second circle is a pretty uniform distribution. `1 - random(random())` must be approximately `sqrt(random())`, iirc that's how you correct for the error demonstrated in the first circle (https://youtube.com/watch?v=4y_nmpv-9lI).
Why are they similar? For a rough idea, random() is a random number between 0 and 1, which on average is 0.5; random(random()) is a random number between 0 and on average 0.5, which on average is 0.25; and so on.
I think that should even make it exactly uniform, but somehow it doesn't look like it. I may have missed a bit somewhere.
So, random(k) should just be k rand() and so random(random()) should be just random() random().
One really fun way to do this is to rewrite using standard exp/ln rules as
# three exponential random variables each with mean 1
k1 = -ln(rand())
k2 = -ln(rand())
k3 = -ln(rand())
# rand() * rand() * rand() written cryptically
exp(-(k1 + k2 + k3))
That these are exponential random variables comes from the inverse-CDF Sampling Theorem.The characteristic function E[exp(itX)] is a Fourier transform of the PDF and for a sum of independent variables it becomes a product,
E[exp(it(X + Y))] = E[exp(itX) exp(itY)] = E[exp(itX)] E[exp(itY)]
for an exponential distribution you have
E[exp(itX)] = ∫{0 → ∞} dx exp(-x) exp(itx) = 1/(1 – it).
So the Fourier transform of the PDF of a sum of n geometric random variables is going to be 1/(1 — i t)^n, which is the characteristic function for a gamma-distributed random variable,[1] and so the corresponding PDF is actually
f_n(x) = x^{n-1}/(n-1)! exp(-x)
[this is not too hard to see above when you realize that the exponent can be factored out as a repeated derivative of 1/(1 — i t) and in Fourier space a derivative corresponds to multiplication by the frequency ... derivatives with respect to t become multiplications by x].
So now we know that the distribution of the product U_n = exp(-G_n) where G_n is a Γ(n, 1)-distributed random variable, we work backwards from the definition:
h_n(u) du = the probability that U_n is between u and u + du
in which case G_n is between -ln(u) and -ln(u + du) = -[ ln(u) + ln(1 + du/u) ] ~= -ln(u) - du/u.
so that's f_n(x) dx where x = -ln(u) and dx = du/u, so that's
h_n(u) = (-ln(u))^{n-1}/(n-1)!, for 0 < u < 1.
and if you wanted the CDF it'd be an incomplete gamma function I think. For n=1 you can see that this recapitulates a uniform distribution but even for n=2 you have -ln(u) being the probability density function which I don't think will give you that sqrt() stuff that you need to get exact uniformity.
If you plot their difference, 1-random(random()) aka 1-random()*random() is empirically skewed slightly larger than 1-random()^2, but I don't know how to analyze it exactly analytically.
I can grok a lot of the dimensional effects of randomness but without these things specified, the picture is rather meaningless to me.
2. The argument is the high end of the range (0 to n [https://processing.org/reference/random_.html])
3. I dunno why, it seems like it's just cool. It seems to demonstrate that random(random(...)) collapses to 0, which is exactly what I expected but it's pretty cool.
The expectation marches by half the distance towards the outer edge each time, so it becomes a soap bubble at a rate of 1/2^n
Which is nice and sorta cool but I'm not quite sure what the "whoa" factor here is. It's like one of those zip cinch tops for those bags. Sorta cool how it works on observation, really cool in detail, but also sorta...meh? At the same time?
Maybe I'm a bit jaded here? Admittedly, a continuous animation of this would be an improvement on the cool factor to me, personally.
You can confirm in a python terminal (or anything else) that the product of n `random()`s decreases more rapidly than 2^-n.
So maybe there's some value in it after all :)
Click the "</>" at the top to read the code.
There's a popular "Let's Code" YouTube channel called The Coding Train that uses it. It's quite acccessible.
random(high)
random(low, high)
https://processing.org/reference/random_.htmlI think this isn't so intuitive because the polar coordinates already imply greater density near center (which could be corrected with a suitable map).
(i am to lazy to register to make a fork, here is the code change):
replace:
let a = random(Math.PI*2);
let r = d * (1 - random());
point(cos(a)*r, sin(a)*r);
with: let x = random(d);
let y = d * (1 - random());
point(x, y);
in every blockyou could even simplify it to:
let x = random(d);
let y = random(d);
point(x, y);
and for more fun apply the nested random() call to both axis: let x = random(random(d));
let y = random(random(d));
point(x, y);I forked it: https://openprocessing.org/sketch/1929579
Fun lil script.
https://media.discordapp.net/attachments/519790546601115649/...
EDIT: Realized I cut off the full script. First two lines are:
var ran = new Random();
var counts = new Dictionary<int,int>();The first picture plots points where radius and angle (in polar coordinates) are uniformly distributed. Of course, this is not uniform in the disc.
I don't have the time right now, but if I do later, I'll type up the math behind what a uniform distribution in the disc looks like, and what's going on in other pictures.
1-Random(Random(Random(Random())))
and not Random(Random(Random(Random())))One such command is "/roll". When this command is followed by a number (n), it generates a random number between 1 and n. This is akin to a digital dice roll, with the number specifying the number of sides on the dice.
For instance, you might decide to start a game with another player where you both start with a number of 500 and wager 100 gold. You would initiate the game by typing "/roll 500" into the chat, which would then generate a random number between 1 and 500. Let's imagine it gives you 137.
The other player then uses this number as the argument for their roll. So they would type "/roll 137". This process continues with each player using the result of the previous roll as the new argument for the "/roll" command.
The game ends when a player rolls a 1, and that player is deemed the loser.
Aesthetics?
P.S. In case anyone is confused, the arg to random is the upper limit (not the seed), and r = diameter * (1 - value)
Not sure I can explain the effect on the other panels since the first iteration is already based on assumptions.
On the first look it looks that random is broken then you realize, no random(n) is a random value between [0;n) so it's behaving exactly right.
It also shows really nice how "naively" choosing random points in a non rectangular shape can easily lead to a non uniform distribution.
> Accidentally(?) shows nonuniform-looking distribution of points from uniform random() due to polar coordinate conversions
> Shows effects of nesting random calls in a way reminiscent of security papers showing design flaws, but it's not really showing that
> Refuses to elaborate further
The more I think about this, the better it is. The imperfection is what makes this little bit of code so interesting to us nerds, while even trolling some people, but we have no idea what the intent was. It's great.
let radius = d * random(random(random()))
instead of
let radius = d * (1 - random(random(random())))
But, if so, probably so much less confusing that folks wouldn't be talking about it here, to be honest.
- random(x) made me think x was the seed. Maybe call it random(0, x) to make it clear to most that you mean min 0 max x.
- The random() probably looks nonuniform to most people. Looking at the code, it's a random angle and length in polar coordinates, with the angle not getting any additional random() wrapping in the other examples. XY coordinates would be clearer.
Fair, but that would be bad design in my opinion. In general you want the random() function to be usable multiple times to get the same sequence after setting the seed once, and not have to specify the seed every time.
But now I see this page has editable code and whatever language it's in does have random(x) taking one arg. So fair enough.
What's interesting is the transforms used to sample in some new space from e.g. uniform random inputs. For instance, disks [1] or hemispheres [2] or an arbitrary density function [3]. Common stuff in light transport simulation, and easy to get wrong.
[1]: https://stats.stackexchange.com/questions/481543/generating-...
[2]: https://alexanderameye.github.io/notes/sampling-the-hemisphe...
[3]: https://en.wikipedia.org/wiki/Inverse_transform_sampling
As you add more randoms, most of the points lie close to the surface.
This is also the case in high dimensional spheres: most of volume lie near the surface of the hyper sphere.
In the random() * random() * random() ... , once you draw at least one number close to 0 (chances will increase as you add more randoms), then your output collapses to a very small number. And in this visualization, 0 is shown as a point at the edge of the circle.
Of course with Euclidean it will as that seems to match our expectations for low dimensional space.
I'm not a mathematician so there is not much more that I could say on the matter at this juncture.
For p goes to infinity, the unit "ball" becomes a "cube" of two units wide per side.
https://en.wikipedia.org/wiki/Volume_of_an_n-ball#Balls_in_L...
https://www.johndcook.com/blog/2010/07/02/volumes-of-general...
let a = random(Math.PI*2);
let r = d * (1 - random());
point(cos(a)*r, sin(a)*r);
(click "</>" in the submission to view source).Here is an example I made to use logistic map for music note generation:
Can someone describe what this is supposed to do?
The fact that random(random()) /looks/ more even in this visualization shows that the actual distribution is not.
I'm putting this in the past tense, it randumb enough times for me.