double operation wrong answer in Java [duplicate] - java

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 6 years ago.
I have 2 numbers stored as Double, 1.4300 and 1.4350. When I subtract 1.4350 - 1.4300, it gives me the result: 0.0050000000000001155. Why does it add 1155 to the end and how can I solve this so that it returns 0.005 or 0.0050? I'm not sure rounding will work as I'm working with 2 and 4 decimal numbers.

Oh, I love these... these are caused by inaccuracy in the double representation and floating-point arithmetic is full of these. It is often caused by recurring numbers in binary (i.e. base-2 floating-point representation). For example, in decimal 1/3 = 0.3333' In binary 1/10 is a recurring number, which means it cannot be perfectly represented. Try this: 1 - 0.1 - 0.1 - 0.1 - 0.1. You wont get 0.6 :-)
To solve this, use BigDecimal (preferred) or manipulating the double by first multiplying it something like 10000, then rounding it and then dividing it again (less clean).
Good question... it has caused huge problems in the past. Missiles overshooting targets, satellites crashing after launch, etc. Search the web for some, you'll be amazed!

This is a common pitfall with some computer representations of fractional numbers, see this question or google for floating point precision.

Double is not the right type for very precision floating point calculations, if you want exact results you have to use BigDecimal.

Related

Java Double Precision: Different formula leads to different result [duplicate]

This question already has answers here:
Rounding Errors?
(9 answers)
Is floating point math broken?
(31 answers)
Closed 6 years ago.
Today I find an interesting fact that the formula will influence the precision of the result. Please see the below code
double x = 7d
double y = 10d
​println(1-x/y​)
println((y-x)/y​)​
I wrote this code using groovy, you can just treat it as Java
The result is
1-x/y: 0.30000000000000004
(y-x)/y: 0.3
It's interesting that the two formulas which should be equal have different result.
Can anyone explain it for me?
And can I apply the second formula to anywhere applicable as a valid solution for double precision issue?
To control the precision of floating point arithmetic, you should use java.math.BigDecimal.
You can do something like this.
BigDecimal xBigdecimal = BigDecimal.valueOf(7d);
BigDecimal yBigdecimal = BigDecimal.valueOf(10d);
System.out.println(BigDecimal.valueOf(1).subtract(xBigdecimal.divide(yBigdecimal)));
Can anyone explain it for me?
The float and double primitive types in Java are floating point numbers, where the number is stored as a binary representation of a fraction and a exponent.
More specifically, a double-precision floating point value such as the double type is a 64-bit value, where:
1 bit denotes the sign (positive or negative).
11 bits for the exponent.
52 bits for the significant digits (the fractional part as a binary).
These parts are combined to produce a double representation of a value.
Check this
For a detailed description of how floating point values are handled in Java, follow Floating-Point Types, Formats, and Values of the Java Language Specification.
The byte, char, int, long types are fixed-point numbers, which are exact representions of numbers. Unlike fixed point numbers, floating point numbers will some times (safe to assume "most of the time") not be able to return an exact representation of a number. This is the reason why you end up with 0.30000000000000004 in the result of 1 - (x / y​).
When requiring a value that is exact, such as 1.5 or 150.1005, you'll want to use one of the fixed-point types, which will be able to represent the number exactly.
As I've already showed in the above example, Java has a BigDecimal class which will handle very large numbers and very small numbers.

Subtracting two decimal numbers giving weird outputs [duplicate]

This question already has answers here:
Whats wrong with this simple 'double' calculation? [duplicate]
(5 answers)
Closed 9 years ago.
While I was having fun with codes from Java Puzzlers(I don't have the book) I came across this piece of code
public static void main(String args[]) {
System.out.println(2.00 - 1.10);
}
Output is
0.8999999999999999
When I tried changing the code to
2.00d - 1.10d still I get the same output as 0.8999999999999999
For,2.00d - 1.10f Output is 0.8999999761581421
For,2.00f - 1.10d Output is 0.8999999999999999
For,2.00f - 1.10f Output is 0.9
Why din't I get the output as 0.9 in the first place? I could not make any heads or tails out of this? Can somebody articulate this?
Because in Java double values are IEEE floating point numbers.
The work around could be to use Big Decimal class
Immutable, arbitrary-precision signed decimal numbers. A BigDecimal
consists of an arbitrary precision integer unscaled value and a 32-bit
integer scale. If zero or positive, the scale is the number of digits
to the right of the decimal point. If negative, the unscaled value of
the number is multiplied by ten to the power of the negation of the
scale. The value of the number represented by the BigDecimal is
therefore (unscaledValue × 10^-scale).
On a side note you may also want to check Wikipedia article on IEEE 754 how floating point numbers are stored on most systems.
The more operations you do on a floating point number, the more significant rounding errors can become.
In binary 0.1 is 0.00011001100110011001100110011001.....,
As such it cannot be represented exactly in binary. Depending where you round off (float or double) you get different answers.
So 0.1f =0.000110011001100110011001100
And 0.1d=0.0001100110011001100110011001100110011001100110011001
You note that the number repeats on a 1100 cycle. However the float and double precision split it at a different point in the cycle. As such on one the error rounds up and the other rounds down; leading to the difference.
But most importantly;
Never assume floating point numbers are exact
Other answers are correct, just to point to a valid reference, I quote oracle doc:
double: The double data type is a double-precision 64-bit IEEE 754
floating point. Its range of values is beyond the scope of this
discussion, but is specified in the Floating-Point Types, Formats, and
Values section of the Java Language Specification. For decimal values,
this data type is generally the default choice. As mentioned above,
this data type should never be used for precise values, such as
currency

Adding and subtracting doubles are giving strange results [duplicate]

This question already has answers here:
Retain precision with double in Java
(24 answers)
Closed 9 years ago.
So when I add or subtract in Java with Doubles, it giving me strange results. Here are some:
If I add 0.0 + 5.1, it gives me 5.1. That's correct.
If I add 5.1 + 0.1, it gives me 5.199999999999 (The number of repeating 9s may be off). That's wrong.
If I subtract 4.8 - 0.4, it gives me 4.39999999999995 (Again, the repeating 9s may be off). That's wrong.
At first I thought this was only the problem with adding doubles with decimal values, but I was wrong. The following worked fine:
5.1 + 0.2 = 5.3
5.1 - 0.3 = 4.8
Now, the first number added is a double saved as a variable, though the second variable grabs the text from a JTextField. For example:
//doubleNum = 5.1 RIGHT HERE
//The textfield has only a "0.1" in it.
doubleNum += Double.parseDouble(textField.getText());
//doubleNum = 5.199999999999999
In Java, double values are IEEE floating point numbers. Unless they are a power of 2 (or sums of powers of 2, e.g. 1/8 + 1/4 = 3/8), they cannot be represented exactly, even if they have high precision. Some floating point operations will compound the round-off error present in these floating point numbers. In cases you've described above, the floating-point errors have become significant enough to show up in the output.
It doesn't matter what the source of the number is, whether it's parsing a string from a JTextField or specifying a double literal -- the problem is inherit in floating-point representation.
Workarounds:
If you know you'll only have so many decimal points, then use integer
arithmetic, then convert to a decimal:
(double) (51 + 1) / 10
(double) (48 - 4) / 10
Use BigDecimal
If you must use double, you can cut down on floating-point errors
with the Kahan Summation Algorithm.
In Java, doubles use IEEE 754 floating point arithmetic (see this Wikipedia article), which is inherently inaccurate. Use BigDecimal for perfect decimal precision. To round in printing, accepting merely "pretty good" accuracy, use printf("%.3f", x).

Java precision during division and multiplication alterneting process [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to resolve a Java Rounding Double issue
Please Help,
I programm some calculator in Java. I use double type. Double has 15 digits after the decimal point. I have problem with the following:
1/3 * 3 = 0.9999999999999999
I need 1/3 * 3 = 1
How can I solve this problem?
I keep result in Double. The same problem I have with other mathematical operations, for example
sqrt(6) = 2.449489742783, and next I square the result and I get: 5.999999999999999
You're dealing with inherent limitations of floating-point arithmetic.
Read the paper What Every Computer Scientist Should Know About Floating-Point Arithmetic.
For equality-checking, you should be using something like abs(x-y) < epsilon rather than x == y
For display purposes, you should round to the nearest decimal place that you actually care about.
Certain numbers cannot be represented exactly in binary floating point. 1/3 is one of them. See http://en.wikipedia.org/wiki/Floating_point For that matter, 1/3 cannot be represented exactly in decimal either.
Your calculator should use a java.text.NumberFormat to present the numbers.
The reason why you are seeing this is due to the computers inability to understand infinity.
A computer has limitations, so it does not understand the fact that 1/3 is never-ending. This causes it to round. This can be solved as Jason S posted above. Using these special class, people have started to program ways to computer whether or not something goes to infinity, then attempt to deal with it.

Floating point Weird Phenomenon in Java [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Strange floating-point behaviour in a Java program
I came across this weird phenomenon in Java. Try this statement in a Java program:
System.out.print(4.0-3.1);
The output will be 0.8999999
Why does this happen? And how can it be changed?
I recommend reading What Every Scientist Should Know About Floating-Point Arithmetic. This is standard behavior for floating point math. Most systems (including Java) use IEEE 754 as the standard representation for floating point numbers. Exact, numerical values are not always perfectly represented by this standard, so you often see slight numerical inconsistencies when printing, as you found here.
This is a typical floating point result runded.
You get different results from Float and Double :
System.out.println(4.0f-3.1f);
System.out.println(4.0d-3.1d);
Output:
0.9000001
0.8999999999999999
This is because 0.1 cannot be represented evenly in base 2, and cause a loss of precision. For example :
System.out.println(2.0f-1.9f);
System.out.println(2.0d-1.9d);
Should both return 0.1 but in fact will output :
0.100000024
0.10000000000000009
You will find your answer behind this link.
TL;DR summary: you will have to learn how floating point is represented in computing so you know why these things happen. This is an artifact of floating point representation and you alter it by not using float types if this kind of result is unacceptable to you.
floating point can't represent the value 0.1 or any multiple of 0.1 exactly. It is base 2 where the number system it is displayed in is base 10. There is some data lost when storing base 10 data in base 2 format.
You are having fun with float types. But in binary. In the decimal system there are periodic numbers. Like 1/3 which is 1.33333 and so on. Some numbers in the decimal system are not periodic, but are periodic in the binary system.
Thus calculation is always inaccurate when there is the possibility of periodic numbers.

Categories

Resources