What can I do?
Unfortunately, nothing for the root problem: in your platform, 1.414 has no exact double representation. You can't run a calculation with "1.414" because you can't place "1.414" anywhere in your double
.
See for example http://www3.ntu.edu.sg/home/ehchua/programming/java/DataRepresentation.html .
What you can do is to keep your number with the maximum precision, and display it with reduced precision. You need to calculate machine precision and keep track of error during computation.
So you'll use 1.413999999999997 and at the end get an answer of, say, 41.99999137; which you'll display with
printf("The answer is %.3f\n", theAnswer);
Or you can change platform (compiler, or math library, or floating point representation, e.g. use long double
where supported), but remember that you can then get 1.414 right at the price of getting, say, 1.873 wrong (have it as 1.87299999999 or 1.87300000001), and the calculation will have more or less the same errors.
You can work in integer arithmetic, multiplying the initial numbers by 1,000,000 (and getting 1414000) or another suitable scale, and then dividing at the end. Integers have a maximum bound, though.
There are also Arbitrary Precision Libraries that use a different internal representation and allow you to specify precision the way you want, for example GMP ( http://gmplib.org/ ). Of course, working with that is more difficult than specifying
op1 = 6.0;
op2 = 7.0;
theAnswer = op1 * op2;
and processing is slower as well, but results are good - or as good as you tell them to be.
Using Floats solves my problem. – bjar-bjar Oct 26 '12 at 10:54