문제

double check =0.615 * 255 -0.515 * 255 -0.100 * 255;
System.out.println(check);

why get -2.8421709430404007E-14? it should be 0.0

도움이 되었습니까?

해결책

Double operation has some precision problem. Use BigDecimal operation instead of double than you will get expected result.

  //double check =0.615 * 255 + -0.515 * 255 + -0.100 * 255;
   BigDecimal check =
             (BigDecimal.valueOf(0.615).multiply(BigDecimal.valueOf(255)))
            .add(BigDecimal.valueOf( -0.515).multiply(BigDecimal.valueOf( 255)))
            .add(BigDecimal.valueOf( -0.100).multiply(BigDecimal.valueOf( 255)));

  System.out.println(check);

Result is : 0.000

다른 팁

Debugging your math:

double check0 = 0.615 * 255;
System.out.println(check0);
double check1 = -0.515 * 255;
System.out.println(check1);
double check3 = -0.100 * 255;
System.out.println(check3);
System.out.println("Result: " + (check0 + check1 + check3));

Output:

156.825
-131.32500000000002
-25.5
Result: -2.8421709430404007E-14

Remember that:

  • multiplication has higher operator priority than addition in Java
  • you should use BigDecimal if you want control over the rounding when performing operations with floating point numbers
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top