4 * Copyright (C) 2009 emlix GmbH, Oskar Schirmer <os@emlix.com>
6 * helper functions when coping with rational numbers
9 #include <linux/rational.h>
12 * calculate best rational approximation for a given fraction
13 * taking into account restricted register size, e.g. to find
14 * appropriate values for a pll with 5 bit denominator and
15 * 8 bit numerator register fields, trying to set up with a
16 * frequency ratio of 3.1415, one would say:
18 * rational_best_approximation(31415, 10000,
19 * (1 << 8) - 1, (1 << 5) - 1, &n, &d);
21 * you may look at given_numerator as a fixed point number,
22 * with the fractional part size described in given_denominator.
24 * for theoretical background, see:
25 * http://en.wikipedia.org/wiki/Continued_fraction
28 void rational_best_approximation(
29 unsigned long given_numerator, unsigned long given_denominator,
30 unsigned long max_numerator, unsigned long max_denominator,
31 unsigned long *best_numerator, unsigned long *best_denominator)
33 unsigned long n, d, n0, d0, n1, d1;
35 d = given_denominator;
40 if ((n1 > max_numerator) || (d1 > max_denominator)) {
59 *best_denominator = d1;
62 EXPORT_SYMBOL(rational_best_approximation);