title: How to multiply a 64 bit integer by a fraction in C++ while minimizing error?
body: <p>Given a 64 bit (signed) <code>long long</code> or <code>__int64</code>, how would you go about multiplying it by an arbitrary fraction while at the same time minimizing error?</p>
  
  <p>Three simple sketches:</p>
  
  <pre><code>int64_t numerator = ...;
  int64_t denominator = ...;
  int64_t x = ...;
  
  // a, lossy double conversion for large values
  double fraction = static_cast&lt;double&gt;(numerator) / static_cast&lt;double&gt;(denominator);
  int64_t result = x * fraction;
  
  // b, divide first, problem if denominator value near (or even larger) x
  int64_t result = x / denominator;
  result *= numerator;
  
  // c, multiply first, problem if multiplication overflows
  int64_t result = x * numerator;
  result /= denominator;
  </code></pre>
  
  <p>I would be fine with truncating the result to the nearest integer if <code>x * n / d</code> mathematically doesn't yield a whole number.</p>