Mechanics of Defect Evolution Library
Loading...
Searching...
No Matches
src
Math
BestRationalApproximation.cpp
Go to the documentation of this file.
1
/* This file is part of MoDELib, distributed under GNU GPL v2. */
2
#include <
BestRationalApproximation.h
>
3
#include <math.h>
4
5
namespace
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
78
BestRationalApproximation::BestRationalApproximation
(
const
double
&
f
,
const
LongIntType
&md)
79
: intPair(rat_approx(
f
, md)),
num
(intPair.
first
),
den
(intPair.second)
80
{
81
}
82
}
// namespace model
BestRationalApproximation.h
model::BestRationalApproximation::den
const LongIntType & den
Definition
BestRationalApproximation.h:32
model::BestRationalApproximation::LongIntType
int64_t LongIntType
Definition
BestRationalApproximation.h:23
model::BestRationalApproximation::num
const LongIntType & num
Definition
BestRationalApproximation.h:31
model::BestRationalApproximation::BestRationalApproximation
BestRationalApproximation(const double &f, const LongIntType &md)
Definition
BestRationalApproximation.cpp:78
f
function int_R syms a b c u real f
Definition
int_R.m:4
a
a
Definition
int_R.m:14
x
x
Definition
int_R.m:12
defectFields.n
int n
Definition
defectFields.py:32
model
Definition
DD_converter.dox:2
k
int k
Definition
triangle.cpp:3300
h
REAL * h
Definition
triangle.cpp:4968
i
int i
Definition
triangle.cpp:3300
first
vertex first
Definition
triangle.cpp:8231
Generated by
1.15.0