Results 1 to 4 of 4
  1. #1
    Tien is offline Member
    Join Date
    Oct 2011
    Posts
    5
    Rep Power
    0

    Default Strange division of doubles

    I have the following very simple Java code:

    double dr = 0.1;
    double x;
    cora = x/dr;

    In a for loop x goes from 0.2 to 0.35. When I divide them, the first two results are perfect, but the next results are not "rounded" but end at .999999999999996.

    Results from Java code:

    cora: 2.0
    cora: 2.5
    cora: 2.9999999999999996
    cora: 3.4999999999999996

    This is a problem because I use (int) to round the results to their lower integer value.

    (int) 2.99...6 = 2 but it should be (int) 3.0 = 3


    What goes wrong?

  2. #2
    doWhile is offline Moderator
    Join Date
    Jul 2010
    Location
    California
    Posts
    1,642
    Rep Power
    7

    Default Re: Strange division of doubles

    It is a fundamental result of floating point math. If you need a rounded int out of it, use the Math.round() method.

  3. #3
    Tien is offline Member
    Join Date
    Oct 2011
    Posts
    5
    Rep Power
    0

    Default Re: Strange division of doubles

    But how do I solve the problem of the division itself? I need the true value of the division, not only for the rounding, but also for a bunch of boundary conditions. If you take, for example, the condition "if (x>=3.0)" element 2.99...6 is excluded, while it should be included since it is actually 3.0! I need this division quite often, so I really need to solve it.

  4. #4
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,361
    Blog Entries
    7
    Rep Power
    20

    Default Re: Strange division of doubles

    cenosillicaphobia: the fear for an empty beer glass

Similar Threads

  1. Help with java division
    By louisw in forum Advanced Java
    Replies: 6
    Last Post: 09-29-2011, 06:09 AM
  2. int division
    By überfuzz in forum New To Java
    Replies: 5
    Last Post: 03-24-2011, 07:10 PM
  3. Issues with Division
    By KnotsaboutWood in forum New To Java
    Replies: 11
    Last Post: 01-31-2011, 03:32 AM
  4. big double division
    By grilo in forum Advanced Java
    Replies: 4
    Last Post: 10-11-2009, 10:07 PM
  5. Problem with division using doubles
    By chrismanahan in forum New To Java
    Replies: 3
    Last Post: 10-10-2009, 09:26 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •