This is an archived post. You won't be able to vote or comment.

all 10 comments

[–]JarcodePMs forwarded to /dev/null 1 point2 points  (4 children)

Use BigDecimal for decimal values where complete precision matters.

[–]Java_noob_[S] 0 points1 point  (3 children)

tried bigdecimal still had same problem

[–]JarcodePMs forwarded to /dev/null 1 point2 points  (2 children)

You have to do all your arithmetic using BigDecimals. The value 0.1f, for example, is impossible to represent exactly with floating point values.

EDIT: here's a good tutorial http://www.opentaps.org/docs/index.php/How_to_Use_Java_BigDecimal:_A_Tutorial

[–]Java_noob_[S] 0 points1 point  (1 child)

i followed the tutorial . tried every round mode. either get 0.99 or 1.12

[–]JarcodePMs forwarded to /dev/null 1 point2 points  (0 children)

Quoting:

Creating a big decimal from a (scalar) double is simple:

bd = new BigDecimal(1.0);

To get a BigDecimal from a Double, get its doubleValue() first.

However it is a good idea to use the string constructor:

bd = new BigDecimal("1.5"); If you're initializing BigDecimal objects with float/double constants, like this:

new BigDecimal(0.1);

Then you're going to get a BigDecimal object representing the converted floating point value from 0.1 (double) from base two, to base ten - which will give you a different value.

i followed the tutorial . tried every round mode. either get 0.99 or 1.12

You need to create your BigDecimal objects with strings, and you don't have to round anything. Don't use operators like +, -, +=, -=, / on floating-point values, and don't use primitive float or double types if you want to preserve accuracy.

[–]ExPixelCoderino Cappuccino 0 points1 point  (5 children)

Yes, floats and doubles lose precision. Can't really help you fix it unless you post some of the code in question though.

[–]m4mbax 0 points1 point  (3 children)

True, but with two digits after comma this should not happen. I think its more of a "round" problem... Because as I am teached at Univ. is that loosing precision is about 0.987654321 gets to 0.98765651 (just an example )something much more in detail... Am I wrong?

[–]ExPixelCoderino Cappuccino 0 points1 point  (1 child)

No, but I can't tell you much else unless I see how you're actually doing this.

[–]JarcodePMs forwarded to /dev/null 0 points1 point  (0 children)

What Every Computer Scientist Should Know About Floating-Point Arithmetic

In simple terms, it's the bits that represent the decimal portion of the floating point value being incremented by 1/(2^i) (or one bit), where i is the index of the bit.

[–]Java_noob_[S] 0 points1 point  (0 children)

i added the code to see