4
* Copyright (C) 2009 emlix GmbH, Oskar Schirmer <os@emlix.com>
6
* helper functions when coping with rational numbers
9
#include <linux/rational.h>
10
#include <linux/module.h>
13
* calculate best rational approximation for a given fraction
14
* taking into account restricted register size, e.g. to find
15
* appropriate values for a pll with 5 bit denominator and
16
* 8 bit numerator register fields, trying to set up with a
17
* frequency ratio of 3.1415, one would say:
19
* rational_best_approximation(31415, 10000,
20
* (1 << 8) - 1, (1 << 5) - 1, &n, &d);
22
* you may look at given_numerator as a fixed point number,
23
* with the fractional part size described in given_denominator.
25
* for theoretical background, see:
26
* http://en.wikipedia.org/wiki/Continued_fraction
29
void rational_best_approximation(
30
unsigned long given_numerator, unsigned long given_denominator,
31
unsigned long max_numerator, unsigned long max_denominator,
32
unsigned long *best_numerator, unsigned long *best_denominator)
34
unsigned long n, d, n0, d0, n1, d1;
36
d = given_denominator;
41
if ((n1 > max_numerator) || (d1 > max_denominator)) {
60
*best_denominator = d1;
63
EXPORT_SYMBOL(rational_best_approximation);