I am solving a question which finds a value k which is correct up to ~4 decimal points. I have initialized k as a double. However, it only takes 2 places after the decimal point. I want to know the reason behind this bizarre behaviour.
I have experimented with different numbers to try to understand why this is happening but was unsuccessful.
#include <bits/stdc++.h>
using namespace std;
double calc_err(double x, double y, double z, double a, double k)
{
return ((y*y)/((z-k)*(z-k)) - (a*a*x*x)/(k*k) - (a*a) + 1.0);
}
int main()
{
int t;
cin >> t;
while (t--)
{
double x, y, z, a;
cin >> x >> y >> z >> a;
double cerrp = 100.0;
double hi = z;
double lo = 0;
while(1)
{
cout << "cerrp : " << cerrp << endl;
double k = (hi + lo)/2;
if (cerrp < 0.00005 && cerrp >= 0.0 )
{
cout << "k final : " << k << endl;
break;
}
cout << "hi : " << hi << endl;
cout << "lo : " << lo << endl;
cout << "k : " << k << endl;
cerrp = calc_err(x, y, z, a, k);
if (cerrp >= 0) hi = k;
else lo = k;
}
}
}
Consider the following input: 1 7390 8573 9287 285
After a certain number of iterations "hi" takes a value 9263.49 and "lo" takes a value 9263.48. Hence I expect "k" to take a value (hi + lo)/2 = 9263.485 but it takes the value 9263.49. Also, note that "cerrp" keeps on changing even when "k" is not changing (all the other parameters are constant). Why is this happening?
Edit: This is different from Is floating point math broken? in that my question is related to the precision of the variable while displaying it while the question in the link is related to the inherent inaccuracies of floating point operations.