Seth Hikari
Seth Hikari

Reputation: 2771

Why is my math with Doubles coming out wrong?

This is how I am creating q

Double q = ((r * (i/5)) + y);

at this point the values of the other variables are

r = 3.470694142992069E-5
i = 1
y = -116.30237535361584

but

q = -116.30237535361584

is there something wrong with this math? ( Java )

q should be -116.30236841222755

Upvotes: 0

Views: 1061

Answers (6)

Bala R
Bala R

Reputation: 109027

Try

Double q = ((r * ((double)i/5)) + y);

Here's the complete code.

class Main
{
        public static void main (String[] args) throws java.lang.Exception
        {
                double r = 3.470694142992069E-5;
                int i = 1;
                double y = -116.30237535361584;
                Double q = ((r * ((double)i/5)) + y);
                System.out.println(q);

        }
}

Output: -116.30236841222755

Upvotes: 5

Quincy
Quincy

Reputation: 1949

maybe you can try

Double q = ((r * i/5.0) + y);

Upvotes: 1

debracey
debracey

Reputation: 6607

i and 5 are both integers, so the (i/5) portion evaluates to an integer (0). That negates the multiplication by r, so you're left with only the value for y.

Upvotes: 6

Zach Rattner
Zach Rattner

Reputation: 21361

Floating point values are notoriously imprecise. The difference you're showing can be expected for double arithmetic. If you really need the extra precision, jquantity is an open source Java library for precise math.

Upvotes: 0

Mark Wilkins
Mark Wilkins

Reputation: 41262

If i is an integer (which seems to be the case), then the i/5 expression will perform integer math resulting in zero.

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799520

i is not a double. Integer division floors. Anything times 0 is 0.

Upvotes: 1

Related Questions