How to get around a Possible Loss of Precision Error in java

281 views Asked by At

I'm working on a scaling system, to scale numbers up 25% and round to the nearest integer, and to do this, I am trying to rely on the loss of precision by transferring a double into an int. Is there any way to get around this? or should I go about it in a different way?

public int[] scaleMarks(int[] marks)
{
    double scale = 1.25;
    double temp1;
    int temp2;

    for(int i = 0; i < marks.length; i++)
    {
        temp1 = marks[i] * scale;
        temp2 = marks[i] * scale; //***Loss of precision here***

        if(temp1-temp2>= 0.5)
        {
            temp2++;
        }
        marks[i] = temp2;

    }


    return marks;
}
3

There are 3 answers

1
rgettman On BEST ANSWER

You need to round the product with Math.round so that it can be casted to an int safely.

marks[i] = (int) Math.round(marks[i] * scale);
0
Patricia Shanahan On

If you want round-to-nearest, rather than truncation, you need to use Math.round.

public class Test {
  public static void main(String[] args) {
    System.out.println((int)0.999999);
    System.out.println(Math.round(0.999999));
  }
}

outputs

0
1
0
Francisco Romero On

You can use Math.round function to avoid it:

(int)Math.round(marks[i] * scale);

EDIT: You will have to cast it to int because if you don't do that the result will be wrong (because scale it's a double).

I expect it will be helpful for you!