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