This time, I will summarize the random function for each language. The reason why it is a random function is that it is often used when creating mini games, and it is one of my favorite functions. There are subtle differences in each language, so I will write an article as a memorandum.
By the way, since the random function also has an algorithm, it is * "pseudo-random number" *, Note that it is not a * "true random number" *.
The JavaScript Math.random () function returns a value greater than or equal to 0 and less than 1.
let num = Math.floor(Math.random() * n) + m;
// n =upper limit, m =lower limit
Math.random () returns in floating point, so use Math.floor () to truncate after the decimal point. "N" sets the upper limit, and "m" sets the lower limit.
let num = Math.floor(Math.random() * 10) + 1;
The point to note is that it produces numbers less than one.
Use the random_int () function to generate pseudo-random numbers in PHP.
$num = random_int(int $min, int $max);
Pass the lower limit in the first argument and the upper limit in the second argument. Returns a random number containing min to max as an integer value.
$num = random_int(1, 10);
It's easy because it includes the specified number.
Java uses the Random () class and nextInt () method found in the java.util package.
int num = new java.util.Random().nextInt(n);
Variables are declared as int type because they are returned as int type. The argument of nextInt () becomes the upper limit value, and a value less than 0 to the upper limit value is returned. Like JavaScript, it does not include the specified upper limit itself!
public class Main {
public static void main(String[] args) {
int num = new java.util.Random().nextInt(10) + 1;
}
}
Pass the value, noting that it does not include the upper limit.
Javascript Generate floating point numbers greater than or equal to 0 and less than 1. Learn as a set with Math.floor ().
PHP Lower limit value, upper limit value Returns an integer value including the specified value.
Java Use the Random () class. Pass the upper limit to the argument of the nextInt () method. Returns an integer greater than or equal to 0 and less than the "upper limit".
At the training school, I asked the teacher, "Why is it less than 1?" The teacher's answer was
"Why? ..."
I wondered if it was less than 1 for some reason, Only the person who made such a language can understand it. I thought.
Since then, I've stopped questioning predefined functions, variables, and constants.
Recommended Posts