Paul Adamson
Paul Adamson

Reputation: 9

Math parsing issues with double precision Java variables

I've got some heavy math to translate, from the apps I originally developed in VB6 to Java, and am running into a few issues with even the most basic equations.

For instance, why does this work,

double QD1=0;
QD1=24+c; QD1=QD1/513;

but this not work

double QD1=0;
QD1=(24+c)/513;

Also, I'm getting some non-linearity out of an equation that is completely linear, using doubles. My system is 64-bit Fedora on a laptop built around 2006 or so. Is this likely to be a processor issue or a coding issue? Would I be better off using C++, or some kind of parser plug in?

Upvotes: 0

Views: 100

Answers (3)

Ned
Ned

Reputation: 957

This time, a direct answer:

...why does this work,

double QD1=0;
QD1=24+c; QD1=QD1/513;

QD1 is clearly a double. To Java, 24 is an integer constant. If c is an integer type, c is added to 24 using integer arithmetic and the result is converted to double and then assigned to QD1. If c is a floating point type, 24 is promoted to double, added to c and the double result is assigned to QD1. Either way, the division of QD1 is a double divided by an integer constant. The integer constant is promoted to double and floating point division is performed with a double result assigned to QD1.

but this doesn't.

double QD1=0;
QD1=(24+c)/513;

In this case, if c is an integer type, the entire expression on the right-hand side operates on integers and returns an integer type. In Java, integer division truncates any fractional part which might result if the division were instead performed using floating point values and operators. Once evaluation of the right-hand side has completed, the integer result is promoted to double before assigning it to QD1, but by then, the fractional part of the intended result has already been lost.

The way to prevent this particular problem in practice is to always provide a fractional part to all integer constants used in floating point calculations. E.g. Change the code in both examples to use 24.0 and 513.0 for the constants. Always do this even in code which works as expected. Future edits may "break" the implementation when integer types are not intended.

Upvotes: 0

Alex
Alex

Reputation: 11579

It should be

double QD1=0;
QD1=(double)(24+c)/513;

You need to cast integer (24+c) to double type.

Read more about it here.

Upvotes: 2

Ned
Ned

Reputation: 957

For a more complete explanation for problems like this, see the answer to: What are the rules for evaluation order in Java?

Upvotes: 0

Related Questions