3

We often have to find divider values in our clock framework which generate a clock rate closest to the target rate, i.e. ABS(target_rate - input_rate / best_div) should be minimal. We are limited to integer arithmetic and use the following formula:

int best_div, input_rate, target_rate;
best_div = (input_rate + target_rate / 2) / target_rate;

We can safely assume that input_rate >= target_rate, input_rate > 0, and target_rate > 0.

However, there are some numbers for which the formula "fails", e.g. input_rate = 12152131, target_rate = 441992. For those numbers the formula will return best_div = 27 whereas 28 would result in a rate closer to 441992.

This leads to two questions:

  1. Why is the formula not correct in this case?
  2. I there a fail-safe formula for finding the best divider? Obviously one could just compute the resulting frequency for both dividers, input_rate / target_rate and input_rate / target_rate + 1 and choose the better one but a simpler, direct formula would be preferred.
bunq
  • 31
  • 2
  • 1
    If `q = (input_rate / target_rate) + i` (using integer division, and with `i` in {0,1}), your current formula minimizes `abs (input_rate - target_rate * q)`, whereas you want to minimize `abs (target_rate - input_rate / q)`, where the division is again integer division. Because of the truncating nature of integer division, the two formulas are *not* equivalent. – njuffa Jun 14 '18 at 19:31
  • I think this question belongs to math.stackexchange.com, because it primarily tries to solve a mathematical problem instead of a programming problem. – MC Emperor Jun 15 '18 at 09:03

0 Answers0