I Love the Log-Normal Distribution
Clicking the video takes you to the WebGL build. I've put this article's sample code on GitHub too, but I don't think it'll be much use.
Hello. I'm Hirayama from the Technology Department.
Today's topic is a light one: an introduction to the log-normal distribution.
Motivation
In my previous article, I used random numbers to decide the drag distance and the long-press duration so that the test would drag and long-press at random.
What would happen if I just used Random.Range() in the ordinary way here?
var distance = Random.Range(0f, 1000f);
var duration = Random.Range(0f, 3f);
Something like this, perhaps. Distance up to 1000 pixels, time up to 3 seconds. But most ordinary input is taps, not drags, right? With the code above the average press time is 1.5 seconds, but a tap almost never lasts 1.5 seconds. That's a long press. The average drag distance is 500 pixels, which is also very much a drag. As it stands, you'd have no choice but to branch into separate cases for taps versus drags and long presses, because almost everything becomes a drag or a long press.
But even for taps, you want the time from press to release to vary, and the finger shifts a little when it's released, doesn't it? So even for taps you want random numbers. And if both are going to use random numbers anyway, wouldn't you rather unify the two?
A similar wish might come up elsewhere too, for example when you want to vary a character's stats. If hit points should be between 80 and 120 and you write Random.Range(80f, 120f), characters with 120 or 80 come out just as often as characters with 100. In a game where you recruit monsters as allies, say, where monsters' stats differ slightly between individuals, you might want to make 120 less likely and cluster them around 100.
Random numbers like the ones Random.Range gives, where every value is equally likely, follow what's called a uniform distribution.

This is a histogram of a uniform distribution. Since they're random numbers there's some unevenness, but you can see the frequency is almost constant from top to bottom.
The normal distribution
If you use Random.Range normally, values near the maximum and values near the average come out with about the same probability. But at least in the tap distance and tap time example, we want the average to be much smaller than the maximum, and we want values near the average to come out often and the maximum to come out rarely. So let's tinker with the distribution.
The most popular distribution in the world of distributions is, without doubt, the normal distribution. Values near the average come up a lot, and the further away a value is, the lower its probability. Yet even wildly distant values never have zero probability.

Looking at the graph, most values gather in the middle, and the probability drops sharply the further from the center you go. In this example the average, that is, the middle, is almost 0 and nearly everything is between -2 and 2, but the maximum is 4.3. Values quite far off do come out once in a while.
Making a normal distribution in code
To generate a normal distribution in a program, if an approximation is fine, you do something like this.
float NormalDistribution()
{
var ret = 0f;
for (int i = 0; i < 12; i++)
{
ret += Random.value;
}
return ret - 6f;
}
Add a random number from 0 to 1 (Random.value) 12 times and subtract 6 to make the average 0, and you get something very close to a normal distribution. You can approximate a normal distribution by rolling lots of dice and adding them up, and this is an example of that. You adjust the spread by multiplying by some suitable value, and shift it by adding the average you want. For the current example, let's try something like this:
var distance = Mathf.Abs(NormalDistribution() * 333f);
var duration = Mathf.Abs(NormalDistribution() * 1f);
We don't need negatives, so I took the absolute value. The most common values should be near zero, so I don't add anything.
The normal distribution from the function above has a standard deviation of exactly 1, so the probability of falling between -1 and 1 is roughly 70%. And there's about a 0.3% probability of not falling between -3 and 3. So multiplying by 333 gives a standard deviation of 333, and the probability of not falling between -1000 and 1000 becomes about 0.3%, which makes 1000 feel like a reasonable maximum. For the time, it's 3 seconds at the longest and usually around 0 seconds, which seems about right.
Deviation scores
The deviation score, which we worried about endlessly in our school days, is a value that expresses how far a student is from the average, assuming students' scores are normally distributed. The average is set at 50, and you add or subtract 10 for each standard deviation away. A deviation score of 70 means two standard deviations away, so in this example a distance of 666 pixels has a deviation score of 70. That's the kind of score that gets you into the University of Tokyo, right? You start to feel that 666 pixels won't come out very often.
And in the monster stats example, if you write
var hp = Mathf.Abs(NormalDistribution() * 10f) + 100f;
then 100 points is a deviation score of 50, 110 is 60, and 120 is 70. 120 won't come out very often, and if 130 comes out, it's a real find.
In the graph earlier, the maximum was 4.3. It's a distribution with standard deviation 1, so that's a deviation score of 90. The sample size is 500,000, so roughly speaking, among 500,000 people there might be about one with a deviation score of 90. Of course, real academic ability isn't perfectly normally distributed.
The average is still too big
This might be fine for monsters, but I'm still not satisfied when it comes to taps. A 30% probability of a distance of 333 pixels or more means "it's nearly always a drag". I want something more extreme, raising the probability of small values and lowering the probability of large ones, but that's hard as things are. For example, if you write
var distance = Mathf.Abs(NormalDistribution() * 5f);
almost everything concentrates below 10 pixels, but then a distance of 1000 pixels becomes hopelessly unlikely. The probability of being more than 4 standard deviations away is about 1 in 15,000. A deviation score of 90 means fewer than 1 in 10,000 people. And at 5 times it's about 1 in 2 million, so it just won't come out. That's a deviation score of 100. With a standard deviation of 5, 1000 pixels is 200 times the standard deviation, so the probability is so low it wouldn't come up even if you waited until the end of the universe.
We need a different distribution.
The log-normal distribution
Enter the log-normal distribution. Simply put, you raise something to the power of the value that came out of the normal distribution.
var x = Mathf.Pow(10f, NormalDistribution());
You might think, "Why 'log' when you're raising to the power of a normal distribution?", but it's the other way around. It means "when you take the log, you get a normal distribution". It's easier to understand if you read it as "the log is normally distributed".
Here I use 10 as the base so it's easy to get a feel for. If NormalDistribution() returns 0, it's 10 to the 0th power, which is 1; if it returns 1, it's 10; if it returns 2, it's 100. The probability of returning 3 or more is about 0.15%, so with about 0.15% probability it's 1000 pixels, with 98% probability it's within 100 pixels, and with 85% probability it's within 10 pixels.
The graph of the log-normal distribution looks like this.

Most values gather toward the bottom, and at the top you can't tell how far it stretches.
Drawing the graph so that it includes the maximum gives this.

There are too few to see, but there is data at the right end too. Most of it gathers toward the bottom. The statistics are shown at the top of the screen, and while the average is 1.2, the maximum is over 20.
That fits the requirement of "mostly small is fine, but once in a while I want a huge one that sticks way out"!
By the way, there's no problem if NormalDistribution() returns a negative: -1 gives 10 to the -1st power = 1/10, or 0.1, and -2 gives 0.01, getting ever smaller. It never becomes exactly 0, but you can pretty much think of it as "0 is the minimum". Drag distances and tap times don't need negatives, so this property of being 0 or more without even taking the absolute value is handy.
That's why the automatic tap sample in the previous article uses this distribution to decide drag distances and tap times. There are surely better distributions, but as a stopgap it does very well.
Where the log-normal distribution can be used
If you google log-normal distribution you'll see that this distribution comes up a lot in problems involving money.
- At some point, everyone has 10,000 yen
- Each year, each person's money goes down or up by some percent
Let this run and you get roughly a log-normal distribution. People who get a streak of large x in "+x%" see their money compound into something amazing, ending up with several or several dozen times what ordinary people have.
As a test, let's compare someone who always got 10% with someone who always got 1%.
- 10% for 40 years → 45 times
- 1% for 40 years → 1.5 times
That's a 30-fold difference. You often hear the line "Asset management matters! Aren't you leaving it sitting in a time deposit?", and this is exactly it (granted, 10% is unheard of these days, but even securing 2% versus leaving it at 0.1% makes quite a difference).
Below is a simulation in a program (press the RandomWalk button).

At first everyone has the same amount, but the gap keeps widening. The graph scales itself, so it's hard to see, but if you watch max you should see the money at the top growing into something amazing.
In fact, if you graph the nation's annual incomes it looks roughly like this, and you can clearly see just how extreme things get for the small number of very rich people.
A man named Drucker wrote in a book something to the effect that "social phenomena follow not the normal distribution but the log-normal distribution" (his exact words were different), and you do see it a lot in "phenomena involving humans" such as money. "The number of retweets a tweet gets", "game sales", "the number of fans a celebrity has" and so on are probably similar. A tiny number at the top have values that are off the scale.
The line "What's wrong with being second?" was probably criticized because society follows the log-normal distribution. First and second place can differ in revenue many times over. Content businesses such as games have to contend with the fact that "revenue is log-normally distributed," that is, "second isn't good enough," which is truly frightening. There are also many natural phenomena that look log-normal, such as "the size of oil fields". "The reserves of the top oil fields alone account for most of the total", so if you happen to find a big one, you've hit the jackpot.
Average and median
When something is log-normally distributed, the average is quite far from the intuitive average, that is, the value "most people have about this much". That's because a small number of the super-rich pull the average up.
Companies sometimes publish their average annual salary, but you usually can't trust that, can you? That may be because salaries are log-normally distributed and the average is pushed upward. You can say "the average game makes this much in sales, amazing", but most are in the red and a few big titles monopolize the profit.
To know "the most typical value" for such phenomena, you need to take the median. This shows up in this sample too:

At the top of the screen there are the average (avg) and the median (med), at 1.27 and 1.00 respectively, quite far apart. The cause is the tiny number of samples hitting 10 or 20. In this example the maximum is 22.8, more than 20 times that of an ordinary person (= the median). Truly a microcosm of society.
In this case the gap is 27%, so in terms of annual income it's like saying the average is 3.81 million yen, but the median, that is, the most typical person, earns 3 million. Annual incomes really do have about that much of a gap, and the income statistics I linked earlier also list the median. Against an average of 5.47 million, the median is 4.27 million, so the gap is about the same (these are statistics from 10 years ago, so the median now is probably lower).
Applications in games
Are there other situations in games where this can be used?
Basically, in any game with "microcosm of society" elements, it can be used for predictions and generating test data. When making dummy user data for a social game, I think setting how heavily each user has played, that is, their amount of in-game resources, according to this distribution would make it look plausible. Reasoning it through, if there's an element like the one shown above, "lots of things that grow by a random few percent every so often", you get a log-normal distribution, and if you think of a structure like "the higher your level, the more experience points you get", the growth over a certain amount of play time should be multiplicative. Predictions become easy, and test data becomes easier to make.
Likewise, if a game contains a pseudo-economy, you could probably predict that the distribution of assets will be roughly log-normal.
And even without a "microcosm of society" feel, if you want "lots of small ones, and occasionally an amazingly big one", it's a good idea to try this first. It doesn't need to be a phenomenon close to the log-normal distribution. People's drag distances and tap times are probably far from log-normal, but it's still useful for making plausible values.
Also, when simulating network wait times while debugging, I think it's good to make the wait times log-normal. You can express the situation common in reality, "the API usually comes back right away, but once in a while you're kept waiting a really long time", with a simple formula.
Closing
Today's post was less a technical talk than a bit of idle chatter.
But I think looking at phenomena with distributions in mind makes a difference when you express them in games too, and it's handy in daily life as well. In my view, there are three important distributions that even amateurs can use: the uniform distribution, the normal distribution, and the log-normal distribution. When something varies, if you think about which distribution its variation resembles, it becomes easier to deal with, and easier to express in a program or predict. For the normal distribution in particular, having an intuitive grasp of "70% within one standard deviation, 95% within two, and almost never beyond four" makes it far more useful. If thinking in deviation scores makes it easier to understand, that's fine too. It's a waste to use something this handy only for exam scores.
Another important piece of knowledge is that adding up lots of uniform distributions gives you a normal distribution. That's the central limit theorem. The behavior you get from rolling dice repeatedly, or from moving randomly by the same amount every frame, is a normal distribution. If you start with everything at 1 and add a random value every frame, the graph looks like this.

It becomes a normal distribution in no time.
Since it's a normal distribution, as we saw above, "the probability drops rapidly away from the center", that is, "things mostly stay near the middle". You can more or less imagine how particles will behave when moved randomly, for example.
Taking this further, it wouldn't be wrong to think "even if something sticks out a bit, it'll even out eventually". My daughter was strikingly tall as a toddler, but she soon settled into the average. Height is known to follow the normal distribution.
On the other hand, in phenomena that follow the log-normal distribution, things that stick out stick out off the scale, so it might be worth putting in the effort to become one of those off-the-scale cases. If you become number one in some field, even if your ability isn't much different from number two, you might get completely different fame or money.
Bonus: computing the normal distribution properly
With the Box–Muller transform you can get a normal distribution exactly rather than approximately. It's probably faster than calling the random number generator 12 times, too. This time I made it possible to choose between this and the approximation. The code looks like this.
float normalDistributionCosine = float.MaxValue; // when it holds MaxValue, a calculation is needed.
float GetNormalDistributionBoxMuller()
{
float ret;
if (normalDistributionCosine != float.MaxValue) // if one made earlier is left over, return it
{
ret = normalDistributionCosine;
normalDistributionCosine = float.MaxValue;
}
else
{
var x = Random.value;
var y = Random.value;
var t0 = Mathf.Sqrt(-2f * Mathf.Log(x));
var t1 = Mathf.PI * 2f * y;
normalDistributionCosine = t0 * Mathf.Cos(t1);
ret = t0 * Mathf.Sin(t1);
}
return ret;
}
A feature of it, and also what makes it awkward to use, is that one calculation gives you two values, but if you don't care about speed, I think it's fine to throw one away. In that case, you can just calculate every time and return either the Cos or the Sin.
Bonus: why adding 0-to-1 random numbers 12 times gives something like a normal distribution with standard deviation 1
Adding a random number from 0 to 1 twelve times and subtracting 6 is, if you share the 6 out among the 12 random numbers, equivalent to adding 12 random numbers from -0.5 to 0.5.
The standard deviation is the square root of the variance. The variance is "the sum of the squares of (each value minus the average)". The average of "a random number from -0.5 to 0.5" is 0, so just squaring the value that came out gives the variance.
So what's the average variance of this random number? You can find it by integrating the variance from -0.5 to 0.5.
Integrating x^2 gives x^3/3. Putting in 0.5 for x gives 1/24, and -0.5 gives -1/24, so subtracting gives 1/12. The width of the integration is 0.5-(-0.5)=1, so this is the average as it is. The variance per number is 1/12, and adding 12 of them multiplies the variance by 12 too, making it 1. The standard deviation is its square root, so it's 1. Hooray!
I learned this from reading Professor Okumura's site and was rather moved. The fact that "adding 12 gives a nice result" comes up all the time if you look it up, but with my math skills I couldn't work out why. But as shown above, it's reasoning you can understand if you think it through properly, and I'm ashamed that I'd given up on thinking it through.
Bonus: damage as a normal distribution
Long ago there was a game called Wizardry. In this game damage is decided by dice, so the variation is huge.
Say there's a weapon that rolls one die per attack. That's a uniform distribution from 1 to 6. You can't predict anything with that. While you're weak you have few attacks, so every time is a gamble, and if you're unlucky you're killed in an instant.
But as the game progresses, the number of attacks increases and it approaches a normal distribution. Even with 1 to 6, with 8 attacks the average is 28; the variance of a die is 35/12 per die, times 8 is 280/12, and taking the square root for the standard deviation gives 4.8. In other words, you can now predict that it'll mostly fall within about 18–38. Stability is strength. Mind you, as the game progresses the chance of being killed in one blow also goes up, so if you let your guard down you still die. It's like how, as you get older, your skills improve and you become stable, while at the same time mysterious burdens such as childcare and health mean you can't let your guard down. Games are a microcosm of life.
In this way, I think the design of distributions can also give a game design its character. I don't know any game other than Wizardry with that much variation, but in Dragon Quest, too, the damage from Woosh-type spells varied oddly widely. I wonder what would happen if you made damage log-normal?
I think knowledge of probability and distributions is useful for game design too, and even if you're taking part as a programmer, it'll come in handy for debugging, building tools, and even building AI.