Why doesn't (int) Math.random()*10 produce 10 in Java? - java

Why the following produce between 0 - 9 and not 10?
My understanding is Math.random() create number between 0 to under 1.0.
So it can produce 0.99987 which becomes 10 by *10, isn't it?
int targetNumber = (int) (Math.random()* 10);

Casting a double to an int in Java does integer truncation. This means that if your random number is 0.99987, then multiplying by 10 gives 9.9987, and integer truncation gives 9.

From the Math javadoc :
"a pseudorandom double greater than or equal to 0.0 and less than 1.0"
1.0 is not a posible value with Math.random. So you can't obtain 10. And (int) 9.999 gives 9

Cause (Math.random()* 10 gets rounded down using int(), so int(9.9999999) yields 9.

Because (int) rounds down.
(int)9.999 results in 9.
//integer truncation

0.99987 which becomes 10 by *10
Not when I went to school. It becomes 9.9987.

Math.floor(Math.random() * 10) + 1
Now you get a integer number between 1 and 10, including the number 10.

You could always tack on a +1 to the end of the command, allowing it to add 1 to the generated number. So, you would have something like this:
int randomnumber = ( (int)(Math.random( )*10) +1);
This would generate any integer between 1 and 10.
If you wanted any integer between 0 and 10, you could do this:
int randomnumber = ( (int)(Math.random( )*11) -1);
Hope this helps!

you can add 1 to the equation so the output will be from 1 to 10 instead of 0 to 9
like this :
int targetNumber = (int) (Math.random()* 10+1);

Related

Why is my implementation of math.random in my class only returning 0? [duplicate]

This question already has answers here:
math.random, only generating a 0?
(4 answers)
Closed 2 years ago.
I've been trying to create a class to roll dice for games, and my code for one aspect of it is:
public int[] yahtzeeRoll() {
int[] rolls1 = new int[6];
for (int i = 0; i < 6; i++) {
rolls1[i] = ((int) Math.random()*6+1);
}
return rolls1;
}
yet, when I call it in the main method, it only returns 1 for each of the values. Why is this? How can I fix my code so that it generates 6 different numbers when I print the array in the main method?
You are casting the double value returned by Math.random() to int before multiplying by 6, and since Math.random() returns a value < 1, casting it to int results in 0.
Change
rolls1[i] = ((int) Math.random()*6+1);
to
rolls1[i] = (int)(Math.random()*6)+1;
The type casting by appending (type) takes precedence over the * 6 bits afterwards. Therefore, the result from Math.random() is always casted into 0 before you multiply it by 6, which turns out to always be 0 as well.
This answer points to this site which explains it quite well.
Either (int) (Math.random() * 6) + 1 or (int) (Math.random() * 6 + 1) would work as you have intended.
Math.random returns a floating point number between 0 and 1 but you are truncating it down to 0 by using (int) type cast before it. Use parentheses around your expression and then prepend (int) to that if you do wish to use integer truncation.
Btw, I think same sequence should be generated at each run if you don't seed the pseudo-random engine, say with current time or something.
Let's look at the expression.
((int) Math.random()*6+1)
Now Math.random() returns a double that is >=0 and <1.
You then cast that result to an int which means it will always become 0.
If you use.
(int)(Math.random()*6+1)
You are taking the double between 0 and 1, multiplying it by 6 (giving 0 ... 6) adding 1 and then casting to an int. This looks more like what you are looking for.
Math.random() returns double value in range [0, 1) (greater than or equal to 0.0 and less than 1.0). Then you cast that double value to int, so it always results in 0. After that you add 1 to it, so the result always remains 1.
You should cast result of multiplication - Math.random() * 6 instead of casting Math.random() return value:
rolls1[i] = (int)(Math.random()*6)+1;
By the way, you should be aware of operators precedence in Java language. You can have a look here: operator precedence to see nice table that shows that casting has a higher priority than multiplication and addition - this is the reason, why (Math.random()*6) is put in parenthesis for casting (this way you avoid casting only Math.random())
PS. There is also a link to table of operator precedence in official Java tutorial, but it doesn't exactly fit to your problem as it doesn't contain operation of casting - this is the reason, why I provided another link firstly.
You can take a clue from the below output presentation which is self explanatory.
Code:
double random = Math.random();
System.out.println("Math.random()>>"+random);
System.out.println("Math.random()*6>>"+random*6);
System.out.println("(int)(Math.random()*6)>>"+(int)(random*6));
System.out.println("Math.random()*6+1>>"+random*6+1); //+1 here is treated as a string by java and will add at the end of the number
System.out.println("(Math.random()*6+1)>>"+(random*6+1)); //number random*6 will be incremented by 1 as enclosing () will treat them as numbers
System.out.println("(int)(Math.random()*6+1)>>"+(int)(random*6+1));
Output:
Math.random()>>0.6793602796545469
Math.random()*6>>4.076161677927281
(int)(Math.random()*6)>>4
Math.random()*6+1>>4.0761616779272811
(Math.random()*6+1)>>5.076161677927281
(int)(Math.random()*6+1)>>5

Can't change Integer to Double, and this cause my code to fail

I'am trying to divide x by 9, and when x divided by 9 returns something bigger than 1, I proceed with my code. But what if x is 10? 10 divided by 9 returns 1,1 which means that you can only make one item and the 0,1 should be returned to you.
Example:
I have 64 of item a and try to create another item b which needs at least 9 of item a to create one item b. If we divide 64 by 9 it returns 7,1 which means that we can get a max of 7 item b. The 0,1 gives me 0.0 when i try to round it up with Math.ceil().
Anyone know how I can get 0,1 of 64 / 9 and round it up to one?
This is what I've tried:
Integer getIronBlocks = ironIngots / 9;
Integer getGoldIngots = goldNuggets / 9;
double ironIngotLeft = Math.ceil(getIronBlocks);
double goldNuggetLeft = Math.ceil(getGoldIngots);
I already know the issue of this code, but don't know how to fix it. Lets say ironIngots = 64 and we divide it by 9 we get 7 not 7,1. Changing Integer getIronBlocks to Double getIronBlocks will raise an error by IntelliJ
you need use double to store the result and divide by double.
int ironIngots = 10;
double getIronBlocks = ironIngots / 9.0;
System.out.println("result : "+ getIronBlocks); // ---> 1.111111
https://ideone.com/Yz4yBO
If you divide by an int the result is an int.
The problem is that by using Integer class, the decimals of the result are lost.
So what you end up doing is rounding up 0 which will give 0 as a result.
Use BigDecimal if you want accuracy in the operation. Or Double, but Double has binary operations issue with accuracy.

Creating random numbers within a range [duplicate]

This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 9 years ago.
I am very new to Java and I am stuck on this, I am using the formula:
min + (int)(Math.random()*(max-min+1))
and I have to write statements that assign random integers to the variable x in the following ranges
1 < x <= 8
1 being min and 8 being max
Am I correct that it would be 1 + (int)(Math.random()*(8-1+1))?
-5 < x <= 3
3 being min and -5 being max
and this would be 3 + (int)(Math.radom()*(-5-3+1))?
Any help would be greatly appreciated.
You want a formula to take a real number in the range [0..1), and return an integer in the range [1..8].
When random() picks a real number it the range [0..1),
and you multiply it by 8,
you get a value in the range [0.0 .. 8.0).
Then you then convert to (int), you have an integer in the range [0 .. 7],
because conversion to (int) rounds using the 'floor' step function.
Add one.
use following code. It will generate nos between 0 and max value supplied.
Random generator = new Random(); //Creates a new random number generator
for(int i=0; i<100; i++){
/**
*Returns a pseudorandom, uniformly distributed int value
* between 0 (inclusive) and the specified value (exclusive), drawn from
* this random number generator's sequence
*/
System.out.println(generator.nextInt(100));
}
Get random value with range ( min, max ] , this is the same with the question.
If JDK 1.7 version is used, then you can use one line code to implement such function:
ThreadLocalRandom.current().nextInt(min, max)+1
If JDK version is under 1.7, we can implement it using the following way.
Random random = new Random();
random.nextInt(max - min) + min +1;
2.Get random value with range [ min, max )
Use,
ThreadLocalRandom.current().nextInt(min, max)
or
random.nextInt(max - min) + min ;
Math.random() gives you between 0 and 1. Multiply this by your range, the size of the range, not the absolute value. If you want 1-10 that's 9, if you want 0-10 that's 10, if you want 5-7 that's 2, etc.
Then add or subtract to go from 0 to the starting value.
If you want 0-9 then you're done (you should have multiplied by 9 in the previous step)
If you want 1-10 then add 1
If you want -5 to 5 then subtract 5
If you want 5-7 then do (Math.random()*2)+5;

Java percent of number [duplicate]

This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 4 years ago.
Is there any way to calculate (for example) 50% of 120?
I tried:
int k = (int)(120 / 100)*50;
But it doesn't work.
int k = (int)(120 / 100)*50;
The above does not work because you are performing an
integer division expression (120 / 100) which result is
integer 1, and then multiplying that result to 50, giving
the final result of 50.
If you want to calculate 50% of 120, use:
int k = (int)(120*(50.0f/100.0f));
more generally:
int k = (int)(value*(percentage/100.0f));
int k = (int)(120*50.0/100.0);
Never use floating point primitive types if you want exact numbers and consistent results, instead use BigDecimal.
The problem with your code is that result of (120/100) is 1, since 120/100=1.2 in reality, but as per java, int/int is always an int.
To solve your question for now, cast either value to a float or double and cast result back to int.
I suggest using BigDecimal, rather than float or double. Division by 100 is always exact in BigDecimal, but can cause rounding error in float or double.
That means that, for example, using BigDecimal 50% of x plus 30% of x plus 20% of x will always sum to exactly x.
it is simple as 2 * 2 = 4 :)
int k = (int)(50 * 120) / 100;
Division must be float, not int
(120f * 50 / 100f)
You don't need floating point in this case you can write
int i = 120 * 50 / 100;
or
int i = 120 / 2;

How can I round manually?

I'd like to round manually without the round()-Method.
So I can tell my program that's my number, on this point i want you to round.
Let me give you some examples:
Input number: 144
Input rounding: 2
Output rounded number: 140
Input number: 123456
Input rounding: 3
Output rounded number: 123500
And as a litte addon maybe to round behind the comma:
Input number: 123.456
Input rounding: -1
Output rounded number: 123.460
I don't know how to start programming that...
Has anyone a clue how I can get started with that problem?
Thanks for helping me :)
I'd like to learn better programming, so i don't want to use the round and make my own one, so i can understand it a better way :)
A simple way to do it is:
Divide the number by a power of ten
Round it by any desired method
Multiply the result by the same power of ten in step 1
Let me show you an example:
You want to round the number 1234.567 to two decimal positions (the desired result is 1234.57).
x = 1234.567;
p = 2;
x = x * pow(10, p); // x = 123456.7
x = floor(x + 0.5); // x = floor(123456.7 + 0.5) = floor(123457.2) = 123457
x = x / pow(10,p); // x = 1234.57
return x;
Of course you can compact all these steps in one. I made it step-by-step to show you how it works. In a compact java form it would be something like:
public double roundItTheHardWay(double x, int p) {
return ((double) Math.floor(x * pow(10,p) + 0.5)) / pow(10,p);
}
As for the integer positions, you can easily check that this also works (with p < 0).
Hope this helps
if you need some advice how to start,
step by step write down calculations what you need to do to get from 144,2 --> 140
replace your math with java commands, that should be easy, but if you have problem, just look here and here
public static int round (int input, int places) {
int factor = (int)java.lang.Math.pow(10, places);
return (input / factor) * factor;
}
Basically, what this does is dividing the input by your factor, then multiplying again. When dividing integers in languages like Java, the remainder of the division is dropped from the results.
edit: the code was faulty, fixed it. Also, the java.lang.Math.pow is so that you get 10 to the n-th power, where n is the value of places. In the OP's example, the number of places to consider is upped by one.
Re-edit: as pointed out in the comments, the above will give you the floor, that is, the result of rounding down. If you don't want to always round down, you must also keep the modulus in another variable. Like this:
int mod = input % factor;
If you want to always get the ceiling, that is, rounding up, check whether mod is zero. If it is, leave it at that. Otherwise, add factor to the result.
int ceil = input + (mod == 0 ? 0 : factor);
If you want to round to nearest, then get the floor if mod is smaller than factor / 2, or the ceiling otherwise.
Divide (positive)/Multiply (negative) by the "input rounding" times 10 - 1 (144 / (10 * (2 - 1)). This will give you the same in this instance. Get the remainder of the last digit (4). Determine if it is greater than or equal to 5 (less than). Make it equal to 0 or add 10, depending on the previous answer. Multiply/Divide it back by the "input rounding" times 10 - 1. This should give you your value.
If this is for homework. The purpose is to teach you to think for yourself. I may have given you the answer, but you still need to write the code by yourself.
Next time, you should write your own code and ask what is wrong
For integers, one way would be to use a combination of the mod operator, which is the percent symbol %, and the divide operator. In your first example, you would compute 144 % 10, resulting in 4. And compute 144 / 10, which gives 14 (as an integer). You can compare the result of the mod operation to half of the denominator, to find out if you should round the 14 up to 15 or not (in this case not), and then multiply back by the denominator to get your answer.
In psuedo code, assuming n is the number to round, p is the power of 10 representing the position of the significant digits:
denom = power(10, p)
remainder = n % denom
dividend = n / denom
if (remainder < denom/2)
return dividend * denom
else
return (dividend + 1) * denom

Categories

Resources