Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiently detect that rational numbers are equal

I have a collection of many rational numbers, with the numerator and denominator of each stored as a large (hundreds or thousands of bits) unsigned integer. I'd like to be able to efficiently test whether any given rational number a/b in the set is equal to any other rational number c/d in the set.

The most straightforward method would be to test whether a*d == b*c, of course, but I'd like something more efficient than computing the full products.

Some notes on my particular use-case:

  • The pairs I'll be testing have a high likelihood of actually being equal (because I'm already precomputing and comparing them by their floating point approximations first), so early-outing if they're unequal won't save me much time.
  • I'm fine with precomputing extra data for each of the numbers, but each number will only be used in a handful of comparisons, so expensive precomputation (such as prime factorization) probably wouldn't be worthwhile.
  • Occasional false negatives would be fine, but false positives are not.

I think this may be theoretically impossible, but throwing it out to the hive mind just in case.

like image 369
Sneftel Avatar asked Nov 21 '16 19:11

Sneftel


People also ask

How do you know if rational numbers are equal?

Two rational numbers are said to be equivalent if their lowest forms are the same. For example, 2/3 and 18/27 are equivalent because when these are reduced to their lowest forms, they give the same value. These numbers are the same as equivalent fractions, such as 1/2, 2/4, and 4/6.

Which methods can we use to compare rational numbers?

To compare any two rational numbers, we follow the following steps: Step 1: Express each of the two given rational numbers with a positive denominator. Step 2: Take the LCM of these positive denominators. Step 3: Express each rational number obtained in step 1 with this LCM as the common denominator.

What do you understand by equality of rational number give some example?

Clearly, the given rational numbers have the same standard form. Therefore, the given rational numbers 14−35 and −2665 are equal.


1 Answers

You can filter out many not equal pairs of fractions by comparing the bit-lengths. Let l(a) = floor(log2(a)) + 1 the bit-length of a. If a/b = c/d than l(a) + l(d) = l(c) + l(b).

You can use this for a speedup when you are first comparing the lengths and comparing the products, only if the sum of the lengths are equal.

like image 187
clemens Avatar answered Sep 29 '22 00:09

clemens