rodz's blog

By rodz, 8 years ago, In English

Consider the following C++ code:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
double f(ll x,ll y,ll p,ll q)
{
    double n = ((1.0 * p) * (1.0*y)) / (1.0*q) - x;
    double d = (1.0 - (1.0*p)/(1.0*q));
    return n/d;
}
int main()
{
	ll x = 1, y = 2, p = 499999999 , q = 500000000;
	cout << fixed << setprecision(6);
	cout << f(x, y, p, q) << endl;
        cin >> x >> y >> p >> q;
	cout << f(x, y, p, q) << endl;
	return 0;
}

When I run it on Custom Invocation with input 1 2 499999999 500000000 it prints two different values. I know floating point calculations may have precision issues but why does it make a difference whether I read the input from stdin or hardcode it into the variables?

Full text and comments »

  • Vote: I like it
  • +11
  • Vote: I do not like it