-1

I am using the following arithmetic to convert a fraction to its hex equivalent:

.142857 * 16 = 2.285712
.285712 * 16 =  4.571429

Where I keep multiplying the remainder until it is either equal to the original remainder or zero.

So I wrote this function to try to perform this arithmetic recursively:

int * getHex(int * arr, double original, double result, int index) {
    double newResult, fraction, integer;
    newResult = result;
    fraction = modf(newResult, &integer);
    cout << "fraction " << fraction << " the result " << rem << endl;
    arr[index] = (int)integer;
    if(fraction == original) cout << "test" << endl;
    if (fraction == 0 || fraction == original) {
       return arr;
    }
    index += 1;
    return resultToHex(hexArr, result, fraction * 16, index);
}

I am calling this method like so:

int * arr = new int[100];
int num = stoi(numerator, nullptr, 16);
int den = stoi(denominator, nullptr, 16);
double rem = 1 + ( (double)(num - den) / den);
double result = rem * 16;

arr = getHex(arr, rem, result, 0);

The problem is that fraction never equals rem being passed in, even though when I cout I see that at some point fraction definitely equals rem. An example of what I am talking about:

Where numerator is 1 and denominator is 7:

rem = .142857
result = 2.28571

Then I call the function, passing in the above as arguments:

getHex(arr, rem, result, 0);

and this is the result of the cout inside getHex:

 the fraction 0.285714 result 0.142857
 the fraction 0.571429 result 0.142857
 the fraction 0.142857 result 0.142857 // the fraction equals the original remainder
 the fraction 0.285714 result 0.142857
 the fraction 0.571429 result 0.142857
 the fraction 0.142857 result 0.142857
 the fraction 0.285714 result 0.142857
 the fraction 0.571429 result 0.142857
 the fraction 0.14286 result 0.142857
 the fraction 0.285767 result 0.142857
 the fraction 0.572266 result 0.142857
 the fraction 0.15625 result 0.142857
 the fraction 0.5 result 0.142857
 the fraction 0 result 0.142857

I cannot figure out why my function continues to execute even though after the third iteration the fraction equals the remainder. I cannot find the bug. What am I missing here?

Mahmud Adam
  • 3,489
  • 8
  • 33
  • 54
  • 1
    [What every computer scientist should know about floating point airthemetic](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – P0W Jan 28 '17 at 18:16
  • You cannot compare equality for doubles, due to computer approximation. You must specify a tolerance and check if their difference is less than the specific tolerance. – Jepessen Jan 28 '17 at 18:17

1 Answers1

1

if(fraction == original) <== you are comparing double values for equality.

You should never do that.

It never works.

There is a multitude of posts on why comparing double or float values for equality does not work.

For example: How dangerous is it to compare floating point values?

Community
  • 1
  • 1
Mike Nakis
  • 56,297
  • 11
  • 110
  • 142