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/export.h>
14 #include <linux/minmax.h>
15 #include <linux/limits.h>
18 * calculate best rational approximation for a given fraction
19 * taking into account restricted register size, e.g. to find
20 * appropriate values for a pll with 5 bit denominator and
21 * 8 bit numerator register fields, trying to set up with a
22 * frequency ratio of 3.1415, one would say:
24 * rational_best_approximation(31415, 10000,
25 * (1 << 8) - 1, (1 << 5) - 1, &n, &d);
27 * you may look at given_numerator as a fixed point number,
28 * with the fractional part size described in given_denominator.
30 * for theoretical background, see:
31 * https://en.wikipedia.org/wiki/Continued_fraction
34 void rational_best_approximation(
35 unsigned long given_numerator, unsigned long given_denominator,
36 unsigned long max_numerator, unsigned long max_denominator,
37 unsigned long *best_numerator, unsigned long *best_denominator)
39 /* n/d is the starting rational, which is continually
40 * decreased each iteration using the Euclidean algorithm.
42 * dp is the value of d from the prior iteration.
44 * n2/d2, n1/d1, and n0/d0 are our successively more accurate
45 * approximations of the rational. They are, respectively,
46 * the current, previous, and two prior iterations of it.
48 * a is current term of the continued fraction.
50 unsigned long n, d, n0, d0, n1, d1, n2, d2;
52 d = given_denominator;
61 /* Find next term in continued fraction, 'a', via
62 * Euclidean algorithm.
69 /* Calculate the current rational approximation (aka
70 * convergent), n2/d2, using the term just found and
71 * the two prior approximations.
76 /* If the current convergent exceeds the maxes, then
77 * return either the previous convergent or the
78 * largest semi-convergent, the final term of which is
81 if ((n2 > max_numerator) || (d2 > max_denominator)) {
82 unsigned long t = ULONG_MAX;
85 t = (max_denominator - d0) / d1;
87 t = min(t, (max_numerator - n0) / n1);
89 /* This tests if the semi-convergent is closer than the previous
90 * convergent. If d1 is zero there is no previous convergent as this
91 * is the 1st iteration, so always choose the semi-convergent.
93 if (!d1 || 2u * t > a || (2u * t == a && d0 * dp > d1 * d)) {
104 *best_numerator = n1;
105 *best_denominator = d1;
108 EXPORT_SYMBOL(rational_best_approximation);