1 // SPDX-License-Identifier: GPL-2.0
5 * Copyright (C) 2009 emlix GmbH, Oskar Schirmer <oskar@scara.com>
6 * Copyright (C) 2019 Trent Piepho <tpiepho@gmail.com>
8 * helper functions when coping with rational numbers
11 #include <linux/rational.h>
12 #include <linux/compiler.h>
13 #include <linux/kernel.h>
16 * calculate best rational approximation for a given fraction
17 * taking into account restricted register size, e.g. to find
18 * appropriate values for a pll with 5 bit denominator and
19 * 8 bit numerator register fields, trying to set up with a
20 * frequency ratio of 3.1415, one would say:
22 * rational_best_approximation(31415, 10000,
23 * (1 << 8) - 1, (1 << 5) - 1, &n, &d);
25 * you may look at given_numerator as a fixed point number,
26 * with the fractional part size described in given_denominator.
28 * for theoretical background, see:
29 * http://en.wikipedia.org/wiki/Continued_fraction
32 void rational_best_approximation(
33 unsigned long given_numerator, unsigned long given_denominator,
34 unsigned long max_numerator, unsigned long max_denominator,
35 unsigned long *best_numerator, unsigned long *best_denominator)
37 /* n/d is the starting rational, which is continually
38 * decreased each iteration using the Euclidean algorithm.
40 * dp is the value of d from the prior iteration.
42 * n2/d2, n1/d1, and n0/d0 are our successively more accurate
43 * approximations of the rational. They are, respectively,
44 * the current, previous, and two prior iterations of it.
46 * a is current term of the continued fraction.
48 unsigned long n, d, n0, d0, n1, d1, n2, d2;
50 d = given_denominator;
59 /* Find next term in continued fraction, 'a', via
60 * Euclidean algorithm.
67 /* Calculate the current rational approximation (aka
68 * convergent), n2/d2, using the term just found and
69 * the two prior approximations.
74 /* If the current convergent exceeds the maxes, then
75 * return either the previous convergent or the
76 * largest semi-convergent, the final term of which is
79 if ((n2 > max_numerator) || (d2 > max_denominator)) {
80 unsigned long t = min((max_numerator - n0) / n1,
81 (max_denominator - d0) / d1);
83 /* This tests if the semi-convergent is closer
84 * than the previous convergent.
86 if (2u * t > a || (2u * t == a && d0 * dp > d1 * d)) {
98 *best_denominator = d1;