I have such a program:

public class Main { public static void main(String[] args) { double nominal = 1.0; double sum = 0; for (int i = 0; i < 10; i++) { sum += 0.1; System.out.println("sum = " + sum); } if (nominal == sum) { System.out.println("Числа равны!"); } else { System.out.println("Числа не равны!"); } } } 

According to the meaning, the result of the addition of a number in the cycle should be 1, but the result is this ..:

 sum = 0.1 sum = 0.2 sum = 0.30000000000000004 sum = 0.4 sum = 0.5 sum = 0.6 sum = 0.7 sum = 0.7999999999999999 sum = 0.8999999999999999 sum = 0.9999999999999999 Числа не равны! 

Why is a double not added as it should?

  • 2
    If you need precision, use BigDecimal . - Arsenicum
  • @Arsenicum, thanks, I'll take a look. - user189127

1 answer 1

Not all numbers can be accurately represented as double, such is the standard for floating-point calculations - IEEE 754

That is why, for exact calculations of fractional numbers (money, commodity units), they use fixed-point numbers, but not double or float .

Floating point numbers are great for processing scientific calculations and numerical simulations.

About comparing floating-point numbers

  • one
    1. How can scientific calculations be carried out if the result is inaccurate? 2. "Numbers with a fixed comma" - are these integers with the type int , long , etc.? - user189127
  • 2
    @ bukashka101 in most cases, an exact result in scientific calculations is not only impossible in principle, but is also not very necessary - andreymal
  • one
    @ bukashka101 Real numbers should be compared with a certain accuracy. You can see about it here , for example (in the section about real primitives). - StateItPrimitive
  • @StateItPrimitive, good :). - user189127
  • @andreymal, why? If I think ... the number of molecules in the fuel for a rocket or something similar, then we need maximum accuracy. - user189127