Mechanics of Defect Evolution Library
Loading...
Searching...
No Matches
BestRationalApproximation.cpp
Go to the documentation of this file.
1/* This file is part of MoDELib, distributed under GNU GPL v2. */
3#include <math.h>
4
5namespace model
6{
7
8 auto BestRationalApproximation::rat_approx(double f, LongIntType md) -> std::pair<LongIntType, LongIntType>
9 {
10 if (fabs(f) < 1.0 / md)
11 {
12 return std::pair<LongIntType, LongIntType>(0, 1);
13 }
14
15 /* a: continued fraction coefficients. */
16 LongIntType a, h[3] = {0, 1, 0}, k[3] = {1, 0, 0};
17 LongIntType x, d, n = 1;
18 long int i, neg = 0;
19
20 if (md <= 1)
21 { // *denom = 1; *num = (LongIntType) f; return;
22 return std::pair<LongIntType, LongIntType>(f, 1);
23 }
24
25 if (f < 0.0)
26 {
27 neg = 1;
28 f = -f;
29 }
30
31 while (f != floor(f))
32 {
33 n <<= 1;
34 f *= 2;
35 }
36
37 d = f;
38
39 /* continued fraction and check denominator each step */
40 for (i = 0; i < 64; i++)
41 {
42
43 a = n ? d / n : 0;
44 if (i && !a)
45 {
46 break;
47 }
48
49 x = d;
50 d = n;
51
52 n = x % n;
53
54 x = a;
55 if (k[1] * a + k[0] >= md)
56 {
57 x = (md - k[0]) / k[1];
58 if (x * 2 >= a || k[1] >= md)
59 {
60 i = 65;
61 }
62 else
63 {
64 break;
65 }
66 }
67
68 h[2] = x * h[1] + h[0];
69 h[0] = h[1];
70 h[1] = h[2];
71 k[2] = x * k[1] + k[0];
72 k[0] = k[1];
73 k[1] = k[2];
74 }
75 return std::pair<LongIntType, LongIntType>(neg ? -h[1] : h[1], k[1]);
76 }
77
79 : intPair(rat_approx(f, md)), num(intPair.first), den(intPair.second)
80 {
81 }
82} // namespace model
BestRationalApproximation(const double &f, const LongIntType &md)
function int_R syms a b c u real f
Definition int_R.m:4
a
Definition int_R.m:14
x
Definition int_R.m:12
int k
REAL * h
int i
vertex first