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