开发者

Why is my math with Doubles coming out wrong?

开发者 https://www.devze.com 2023-03-01 00:19 出处:网络
This is how I am creating q Double q = ((r * (i/5)) + y); at this point the values of the other variables are

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 -开发者_Go百科116.30236841222755


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.


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


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


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


maybe you can try

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号