Dice rolls, stock prices, human behavior, plants and animals, mountains and rivers, the shape of buildings and cities, the world is full of unpredictable things and countless variations. To handle such a kind of nature and complexity in computers, we often use random numbers

サイコロや株価、人の行動、動植物や山や川などの地形、建物や街の形、世の中は予測できないものや無数のバリエーションで溢れています。コンピュータでこうしたある種の自然さ、複雑さを扱うためには乱数がよく用いられます。

IMG_1945.png

Simple random function

単純なランダム関数

Let's start with a simple random function. Actually, it is not possible to generate perfectly random numbers with a computer, but most languages and environments provide pseudo-random functions with sufficient quality. If a function is not available, for example in GLSL, you can use well-known methods such as those described in The Book of Shaders.

まずは単純なランダム関数から始めましょう。実はコンピュータで完全な乱数を発生させることはできないのですが、大抵の言語や環境には十分な性能の疑似乱数が用意されています。GLSLなど、そのような機能が用意されていない場合には The book of shaders に載っているようなよく知られた方法を使うこともできます。

<aside> 💡 A simple random function here refers to one in which every value occurs at approximately the same probability. ここでいう単純なランダム関数とは、どの値もほぼ同じ確率で発生するようなものを指します。

</aside>

Take a look at the sample below. This example uses p5.js's random() function to generate random numbers between 0 and 1, and graphs the occurrences of the values. The vertical bars are in increments of 0.01, with the left end corresponding to the occurrences of the numbers greater than 0.00 and less than 0.01, and the next to that greater than 0.01 and less than 0.02, and so on. The height is adjusted so that the bar with the highest number occupies the full length.

Despite some unevenness, you can see that all numbers occur with roughly the same probability.

下のサンプルを見てみましょう。この例ではp5.jsのrandom()を使って0から1までの数値をランダムに発生させ、値の出現回数をグラフにしています。縦棒は0.01刻みで、左端は0.00以上から0.01未満の間の数が発生した回数、その次は0.01以上、0.02未満に対応しています。高さは最も発生回数が多い棒が縦いっぱいになるように調整されています。

凸凹がありながらも全ての数が大体同じ確率で発生しているのがわかります。

let v = random(1);

https://codepen.io/kynd/pen/MmZPWr