1
2
3
4
5
6
7
8
9#include <linux/rational.h>
10#include <linux/compiler.h>
11#include <linux/export.h>
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30void 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)
34{
35 unsigned long n, d, n0, d0, n1, d1;
36 n = given_numerator;
37 d = given_denominator;
38 n0 = d1 = 0;
39 n1 = d0 = 1;
40 for (;;) {
41 unsigned long t, a;
42 if ((n1 > max_numerator) || (d1 > max_denominator)) {
43 n1 = n0;
44 d1 = d0;
45 break;
46 }
47 if (d == 0)
48 break;
49 t = d;
50 a = n / d;
51 d = n % d;
52 n = t;
53 t = n0 + a * n1;
54 n0 = n1;
55 n1 = t;
56 t = d0 + a * d1;
57 d0 = d1;
58 d1 = t;
59 }
60 *best_numerator = n1;
61 *best_denominator = d1;
62}
63
64EXPORT_SYMBOL(rational_best_approximation);
65