LoginSignup
1
0

Math.random()を使ってみた

Last updated at Posted at 2024-01-09

はじめに

Math.random()の基本的な使い方や活用方法などの基礎的な知識についてまとめました。

Math.random()とは

Math.random()関数は、0 以上 1 未満 (0 は含むが、 1 は含まない) の範囲で
浮動小数点の擬似乱数を返してくれます。

例えば...

Math.random()実行例
//0以上1未満の値の取得
console.log(Math.random());
//0.38639513326188446

このように0.38639513326188446という値を返してくれます。

ですが、Math.random()のみでは0以上1未満の範囲の乱数しか返してくれません。

そこで、、


Math.random()に掛け算をしてみましょう。

Math.random()の値に掛け算をすることで、範囲の拡大をすることができます。
例えば.. 0以上10未満の値を取得するには...

Math.random()実行例
//0以上10未満の値の取得
console.log(Math.random() * 10);
// 1回目 7.4598107037841155
// 2回目 9.661357458837156
// 3回目 2.5801459117464254

これで、0以上10未満の値を返してくれるようになりました。

Math.random()の値に掛け算をすることで、範囲の拡大をすることができます。

つまり、かける値により自由に乱数の範囲を拡大できるということになります。

ただ、長々と羅列された少数が気になりますね...

そこで、、


整数を取得するにはMath.floor()を使ってみましょう。

Math.floorを使うことで、小数点以下を切り捨てることが可能になります。
では、先ほどの0以上10未満の値を取得していたコードに使ってみましょう。

Math.random()実行例
//0以上10未満の値の取得
console.log(Math.floor(Math.random() * 10));
// 1回目 9
// 2回目 4
// 3回目 7

小数点以下を切り捨てることができました。

10をかけても10は取得できない
Math.randomに×10をした場合
0.99999..にいくら10をかけても10にはならないので
Math.floorを使用しても整数の10を取得することはできません。

知っておこう
0~10の整数を取得する場合(11をかける)
console.log(Math.floor(Math.random() * 11));
1~10の整数を取得する場合(10をかけて+1する)
console.log(Math.floor(Math.random() * 10 +1));


おまけ

Math.randomでさいころ

Math.random()実行例
//さいころの出目である1~6の値を取得
console.log(Math.floor(Math.random() * 6) + 1);

おまけ2

Math.randomでチンチロ

コード
//1~6の整数を取得するコード3つを別々の変数に保存
let die1 = Math.floor(Math.random() * 6) + 1;
let die2 = Math.floor(Math.random() * 6) + 1;
let die3 = Math.floor(Math.random() * 6) + 1;
//tintiro()という関数に保存
function tintiro() {
   let die1 = Math.floor(Math.random() * 6) + 1;
   let die2 = Math.floor(Math.random() * 6) + 1;
   let die3 = Math.floor(Math.random() * 6) + 1;
}
//console.logで出目の結果を表示させる
function tintiro() {
   let die1 = Math.floor(Math.random() * 6) + 1;
   let die2 = Math.floor(Math.random() * 6) + 1;
   let die3 = Math.floor(Math.random() * 6) + 1;
   console.log(`(${die1} ,${die2}, ${die3})`);
}

実行結果

image.png
見事にピンゾロもでました^^


参考


終わりに

最後まで読んでいただきありがとうございました。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0