Reputation: 2771
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
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
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
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
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
Reputation: 799520
i
is not a double. Integer division floors. Anything times 0 is 0.
Upvotes: 1