开发者

Java calculating invalid results

开发者 https://www.devze.com 2023-03-21 17:10 出处:网络
I am trying to determine the sign of a number to use in a later calculation. I have code similar to the following:

I am trying to determine the sign of a number to use in a later calculation.

I have code similar to the following:

double value = someClass.someGetterMethod();
double sign = value / Math.abs(value);

I have also tried:

double sign = (value < 0) ? -1d : 1d;

Not always, but sometimes value is positive and sign is negative.

Both variables are on the local stack in a non-static method, so I don't believe that there's a race condition.

Unfortunately, I cannot release the full source and I haven't been able to replicate this in a smaller example. I suspect my environment has something to do with it:

The code in question is packaged into a jar, which is then loaded as a zipgroupfileset into a plugin jar file, which is loaded by netLogo as an "extension" (plugin). So NetLogo is launched, which loads the plugin jar t开发者_Go百科hat contains the class with this code.

NetLogo requires that any plugins need to be compiled for a 1.5 target, so I have that set for both the lib and the extension in my ant build files.

I connect my netbeans debugger by modifying the netlogo vmargs to allow remote debugging

-Xdebug
-Xrunjdwp:transport=dt_socket,address=1000,server=y,suspend=n

I am truly stumped. Is this a problem with how the debugger is displaying the variables? Maybe a problem with NetLogo's 1.5 compilation target requirement?

Any ideas?

Thank you


It could indeed be a display issue as I don't see how the code in question can have the behaviour you describe.

If I were troubleshooting this, I'd make the variables final and would compute sign right after value:

final double value = someClass.someGetterMethod();
final double sign = (value < 0) ? -1d : 1d;

Lastly, I'd print out both variables right after the assignment to sign. If, having done all this, you can trigger the printing of value and sign with inconsistent signs, then something is seriously, seriously wrong.

P.S. I would urge you to consider switching to Math.signum. It probably won't fix your current issue, but it'll handle zeroes and NaNs a bit more gracefully.


A solution that should allow you to remove all ambiguity would be to convert the value to the raw long and check the value of the signed bit:

long rawValue = Double.doubleToRawLongBits(value);
boolean isNegative = (rawValue & 0x8000000000000000L) != 0;


Why is sign a double? would an int work for you?

Your first way of calculating the sign could be prone to rounding errors due to the nature of float/double numbers. I'd say go with the second way:

double value = someClass.someGetterMethod();
int  sign = (value < 0) ? -1 : 1;

Maybe this will give you better results.

0

精彩评论

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