Edit: I've realised that I'm working with the type long double
and not just double
which does make a difference. I've also added an example from my program below that reproduces the error in question.
Note: I'm currently working in C++11 and using GCC to compile.
I'm dealing with a situation where the result varies between the below two calculations:
value1 = x * 6.0;
double six = 6.0;
value2 = x * six;
value1 != value2
Where all variables above are of type long double
.
Essentially, I wrote a line of code that gives me an incorrect answer when I use 6.0 in the actual calculation. Whereas, if I assign 6.0 to a variable of type long double first then use that variable in the calculation I receive the correct result.
I understand the basics of floating point arithmetic, and I guess it's obvious that something is happening to the bits of 6.0 when it is assigned to the long double type.
Sample from my actual program (I left the calculation as is to ensure the error is reproducible):
#include <iomanip>
#include <math.h>
long double six = 6.0;
long double value1;
long double value2;
value1 = (0.7854 * (pow(10, 5)) * six * (pow(0.033, 2)) * 1.01325 * (1.27 * 11.652375 / 1.01325 - 1.0));
value2 = (0.7854 * (pow(10, 5)) * 6.0 * (pow(0.033, 2)) * 1.01325 * (1.27 * 11.652375 / 1.01325 - 1.0));
std::cout << std::setprecision(25) << value1 << std::endl;
std::cout << std::setprecision(25) << value2 << std::endl;
Where the output is:
7074.327896870849993415931
7074.327896870850054256152
Also, I understand how floating point calculations only hold precision up to a certain number of bits (so setting such high precision shouldn't effect results, e.g. after 15-17 digits it should really matter if numbers vary but unfortunately this does affect my calculation).
Question: Why are the above two code segments producing (slightly) different results?
Note: I'm not simply comparing the two numbers with ==
and receiving false
. I've just been printing them out using setprecision
and checking each digit.