# Trouble With Doubles

• August 8th, 2012, 07:04 PM
TheSlowLearner
Trouble With Doubles
No rhyme intended.

Code java:

```import java.util.Scanner;   public class CalculatorProgram { public static void main(String[] args) { Scanner input = new Scanner(System.in); double firstNumber, secondNumber, answer;   System.out.println("Enter the first number:"); firstNumber = input.nextDouble();   System.out.println("Enter the second number:"); secondNumber = input.nextDouble();   answer = firstNumber + secondNumber; System.out.println(answer); } }```

When given two doubles, this code occasionally gives an answer that is incorrect (unless I'm seriously overlooking something math-wise). For instance, I gave it 23.2 and 26.4 and it gave an answer of 49.599999999999994. Can you think of any reason why the answer is not a double and also incorrect?
• August 8th, 2012, 08:58 PM
helloworld922
Re: Trouble With Doubles

Some suggested reading: What Every Computer Scientist Should Know About Floating-Point Arithmetic

Computers represent real numbers using floating point notation. However, this method has discretization limits. Basically, you can't represent every possible number. So the results of floating point operations aren't always completely correct. They're fairly close, though. For example, the printed result is off by 0.000000000000006.
• August 9th, 2012, 10:46 PM
TheSlowLearner
Re: Trouble With Doubles
I feel really stupid having to have a primitive type defined, but then what exactly is a double? I thought it was a number with a decimal point rounded to the second decimal place.

Also, why does floating point notation lead to errors? I could understand in very large numbers, but for numbers with only two decimal points?
• August 9th, 2012, 11:15 PM
jps
Re: Trouble With Doubles
Some time invested on your favorite search engine would better answer your question than a forum. Spend some time looking up double and there are many lengthy explanations about what happens. Did you try the link posted by helloworld922 above? If not, read that. Also read this.
• August 10th, 2012, 12:25 AM
helloworld922
Re: Trouble With Doubles
A double is a floating point number. However, it's "bigger" (i.e. takes up more memory) so can more precisely represent numbers. However, in the end it's still limited in what numbers it can represent.

It leads to errors because of several possibilities:

1. One or both of the numbers can't be represented exactly using floating point notation.
2. The result can't be represented exactly using floating point notation.
• August 13th, 2012, 10:17 AM
TheSlowLearner
Re: Trouble With Doubles
Ok, thanks for the help everyone. This one is solved now.