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:
- Why is the formula not correct in this case?
- 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
andinput_rate / target_rate + 1
and choose the better one but a simpler, direct formula would be preferred.