0

I have created the next code, where I have an ArrayList of Doubles "solution". I want to multiply all the doubles inside this ArrayList. For example, if the solution is [0.9,0.5,0.2], the code returns "0.09000000000000001" and not the real result of 1*0.9*0.5*0.2 = 0.09

    double actualCost = 1;
    for(int j = 0; j < solution.size(); j++) {
        actualCost *= solution.get(j);
    }
    return actualCost;

I don't know why I have this problem, if someone can help me to fix it I'll really appreciate it.

Thanks in advance.

(sorry for my english lvl)

  • 2
    Welcome to the joys of floating point representation in computers. It's "just one of those things" that approximations have to be made, and sometimes this means that miniscule fractions of a value are added in or taken away when math is performed because not every number can be represented with 100% accuracy.. Round the values when you want to use them – Caius Jard Jan 04 '19 at 18:52
  • 1
    Are you able to switch from `double` to something like `BigDecimal` class? – Nicholas Hirras Jan 04 '19 at 18:52
  • @CaiusJard How I round them? – theMaximumForce Jan 04 '19 at 18:54
  • @NicholasHirras I have to use them as doubles because of code after this function :( – theMaximumForce Jan 04 '19 at 18:55
  • 1
    @AndresLuengoBlazquez: The [floating-point-gui.de](https://floating-point-gui.de) [cheat sheet for Java](https://floating-point-gui.de/languages/java/) contains examples of how to round and also how to use `BigDecimal`. If your code is working with money or anything else that is a *discrete* measurement (as opposed to a sample of a *continuous* variable), you really should switch to using `BigDecimal`, because `double` is simply the wrong tool for the job in that case. – Daniel Pryden Jan 04 '19 at 18:58

0 Answers0