开发者

Is there any difference of the floating point type between Java and C?

开发者_开发问答I am importing a project from C to Java which involves a lot of floating-point arithmetic.

Are there any special rules need to be taken care of about translating the C floating-point type into Java?


Java has rules governing whether intermediate results in floating-point computations may use higher precision than the end result or not. You should study the strictfp keyword.


If your application was intended to run on multiple platforms. I'm not sure about C, but in java, precision depends on the platform, exactly, on some platforms, calculations may be more precise than on the others, thus resulting comparisons to be false instead of true. To address this problem there is a strictfp modifier that can be applied to variable or a method and that makes precision constant, so your comparison operations on float will produce the same results on all platforms.


Don't worry, there are not special rules needed.


Further to the point about comparing floating point numbers, the following code is the usual way it is done:

public boolean floatEquals(float a, float b, float epsilon) {
    return Math.abs(a-b) < epsilon;
}

Epsilon is a small number, e.g 0.00001

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜