The attached screenshot shows an error of .000002 when adding 12.6 and 9.3.
Some results compute perfectly though. 11.25 + 13.5 gives 24.75, but 111.3 + 50.9 gives 162.20001
The relevant code is:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// First we define float variables.
float num1, num2, result;
// We have to parse the text to a type float.
num1 = Float.parseFloat(jTextField1.getText());
num2 = Float.parseFloat(jTextField2.getText());
// Now we can perform the addition.
result = num1+num2;
// We will now pass the value of result to jTextField3.
// At the same time, we are going to
// change the value of result from a float to a string.
jTextField3.setText(String.valueOf(result));
}
I'm happy to post all my source code if required, though I have not deviated from the exercise except that my buttons 1 and 2 are swapped around, but I cannot see how that would matter.
Most decimal numbers cannot be accurately represented by a computer - at least when using the IEEE standard on how to do it. Basically, they just get 'close enough'. 0.5 and 0.25 can be, since they represent powers of 2 (2^-1 and 2^-2 respectively), but everything else pretty much has some round off error.
Never ascribe to malice that which can be adequately explained by stupidity.
A computer can only store floating point numbers as a summation of a * 2^i, with a being either 0 or 1 and i being any integer value. For byte, short, int and long i is limited to non-negative numbers. For short and double it's also possible to use negative number, leading to 1/2, 1/4, 1/8 etc.
Because of this, a computer has as much trouble writing 1/10 (0.1) fully as we have writing 1/3 fully. 1/10 is 1/16 + 1/32 + 1/256 + 1/512 + ...
If we translate this to binary, using 0.1 being 1/2, 0.01 being 1/4 etc then 1/10 is 0.000110011001100110011... At some point it has to truncate, just like we truncate 1/3 to 0.3333333333... This truncation causes the errors, just like we wouldn't get 1 if we would multiply 0.3333333333 by 3.
That's because I don't know that FAQ by heart and was too lazy too look it up. Strangely, I wasn't too lazy too type in my full answer. Guess I'm a complex person.