Question:
What is the error message: Possible Loss of precision?
?
2013-01-23 05:48:33 UTC
public class SecondBiggest{
public static void main(String[]args){
int[]big=new int[30];
for(int x=0; x<30; x++){
int y=((Math.random()*100)+1);
big[x]=y;
System.out.println(big[x]);
}
}
}
I Wrote this and it said I have a possible loss of precision on line five. What does this mean and what do I do?
Four answers:
Smart Rump
2013-01-23 05:52:10 UTC
You're basing your algorithm on a .random function. The results it will output will probably not be able to be replicated (as in, the ability to input the same thing on different machines or instances of the program and get the same exact result) and also they would be subject to entropy. That's why it warns you - loss of precision - unreliable results and not recommended for scientific use.
Kaydell
2013-01-23 22:03:07 UTC
Math.random() returns a double and so the following expression:



((Math.random()*100)+1);



is a double.



y is an int. So you are trying to assign a double to an int. A double can have a whole part and a fractional part such as in:



3.14



3 is the whole part and .14 is the fractional part. If you tried to do the following assignment:



int y = 3.14;



You'd get the same error because y is an int, it can only hold the whole part of the decimal number and the .14 would be lost. This is the loss of precision.



If you really want to chop off the fractional part of a double and assign the whole part to an int, you can do a type cast:



int y = (int)3.14;



This converts the double to an int. It doesn't round, it chops off the fractional part of the double.



In your code, it would look like this:



int y=(int)((Math.random()*100)+1);



That should do it.
husoski
2013-01-23 14:02:26 UTC
The Math.random() method returns a double value (between 0 and 1) and that makes the entire expression double. (The 100 and 1 constants are implicitly converted to 100.0 and 1.0, respectively.)



You are trying to store that double result into an int variable. Use a typecast to get rid of the message:



y = (int)(Math.random()*100 + 1);
2013-01-23 13:57:39 UTC
Ii think it has to do with the Y=math.random

it should be like this

y=(int)(math.random()x100+1)



Ii know im not trying it right but all that is important is int...



double works better...it can't devide into the decimal...



use double!


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...