Suppose we have the equation y = k1 * x + b1 = k2 * x + b2. Let's calculate x in floats. I know that it's a bad choice, but I want to understand the reason for results I get. Also let's calculate y using this x and then do the same, but with double(x). Consider this code:
std::cout.precision(20);
float k1, b1, k2, b2;
std::cin >> k1 >> b1 >> k2 >> b2;
float x_f = (b2 - b1) / (k1 - k2);
double x_d = x_f;
printFloat(x_f); // my function which prints number and it's binary representation
printDouble(x_d);
float y_f = x_f * k1 + b1;
double y_d = x_d * k1 + b1;
printFloat(y_f);
printDouble(y_d);
And with k1 = -4653, b1 = 9968, k2 = 520, b2 = -1370 surprisingly got the following results:
x_f = 2.19176483154296875 01000000000011000100010111100000
x_d = 2.19176483154296875 0100000000000001100010001011110000000000000000000000000000000000
y_f = -230.2822265625 11000011011001100100100001000000
y_d = -230.28176116943359375 1100000001101100110010010000010000110000000000000000000000000000
Whereas more precise answer (calculated with Python Decimal) is:
x = 2.191764933307558476705973323023390682389
y = -230.28223468006959211289387202783684516
And the float's answer is closer than the double's one! Why is this happening? I've debugged with gdb (compiled on 64-bit Ubuntu 14.04 g++ 4.8.4) and viewed the instructions, and they are all ok, so it's due to multiplication.