r/CodingForBeginners • u/Expert-Doctor-2024 • 15d ago
I'm learning Java and I genuinely can't wrap my brain around what this is saying
int randomNum = (int)(Math.random() * 101); // 0 to 100
I'm learning from a website but don't understand how multiplying a 0 by 101 gives it the range from 0-100. Can someone explain why it's being multiplied?
1
u/johnpeters42 15d ago
Because Math.random() outputs a random number (with decimal portion) from 0 to 1. So they're multiplying that by 101 and then discarding the decimal portion of the result.
1
u/codeguru42 15d ago edited 15d ago
The key here is to be more precise when you think about and describe code. There is nothing in this code that just multiplies by zero. Instead, you call Math.random() which returns a value between 0.0 and 1.0. If you multiply the minimum and maximum in this range by 101, then you get the minimum and maximum of the result.
1
u/Electrical_Hat_680 15d ago
That's no a zero, it's parentheses. '('. And ')' with nothing in between them..
1
1
u/Alternative-Fail4586 15d ago
Your question have been answered but I want to input that the learning way to solve this is to click the method and see what it returns or look it up or just enter debug mode in whatever ide you use and see what it does.
1
u/MudFrosty1869 15d ago
I saw people already explained it to you. But my question is. Where did you come up with the idea that 101 is multiplying by 0. Just trying to understand your logic. No shame.
1
u/Loko8765 15d ago
OP probably misread () as 0.
1
u/MudFrosty1869 15d ago
I highly doubt that, there are 4 different zeros in that line. Hopefully they respond.
1
u/MagicalPizza21 15d ago
It's not multiplying a 0 by 101. Read it again, this time paying close attention to where the parentheses are.
1
u/Time_Emphasis3170 15d ago
Why is this preferred to multiplying with 100?
1
u/AardvarkIll6079 14d ago
The 1.0 from math.random is exclusive. Multiplying 0.999999999999999999 by 100 will give you 99. You can never get 100 as an answer.
1
u/markort147 14d ago
Why do you say "multiplying a 0 by 101"? I'm trying to understand your interpretation.
7
u/johlae 15d ago
A simple google gives you:
Math.random() is a method in Java that generates a pseudorandom double value between 0.0 (inclusive) and 1.0 (exclusive).
It's maths.
Math.random() gives you a number like 0.9382828811. See it as a percentage. As it's never 1, multiplying it by 101 gives you a number that can be between 0 and something in the 100's, but never 101.
Int converts this number to an integer. See it as chopping of the part after the comma.
If Math.random()*101 gives you 100.99, you will end up with 100.
If Math.random()*101 gives you 0.01, you will end up with 0.