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