Search code examples
mathfloating-pointdivision

How to keep decimal accuracy when dividing with floating points


I am working on a project, and I need to divide a very large 64 bit long value. I absolutely do not care about the whole number result, and only care about the decimal value. The problem is that when dividing a large long with a small 64 bit double floating point value, I loose accuracy in the floating point value due to it needing to store the whole numbers.

Essentially what I am trying to do is this:

double x = long_value / double_value % 1;

but without loosing precision the larger the long_value is. Is there a way of writing this expression so that the whole numbers are discarded and floating point accuracy is not lost? Thanks.

EDIT: btw im out here trying to upvote all these helpful answers, but I just made this account for this question and you need 15 reputation to cast a vote


Solution

  • If your language provides an exact fmod implementation you can do something like this:

    double rem = fmod(long_value, double_value);
    return rem / double_value;
    

    If long_value does not convert exactly to a double value, you could split it into two halves, fmod them individually, add these values together and divide that sum or sum - double_value by double_value.

    If long_value or double_value is negative you may also need to consider different cases depending on how your fmod behaves and what result you expect.