DGtal
2.2.0
Toggle main menu visibility
Loading...
Searching...
No Matches
approximation.cpp
Go to the documentation of this file.
1
47
50
#include <cstdlib>
51
#include <cmath>
52
#include <iostream>
53
#include <iomanip>
54
#include "DGtal/arithmetic/LighterSternBrocot.h"
55
#include "DGtal/base/StdRebinders.h"
57
59
60
using namespace
DGtal
;
61
63
64
void
usage
(
int
,
char
** argv )
65
{
66
std::cerr <<
"Usage: "
<< argv[ 0 ] <<
" <floating point number>"
<< std::endl;
67
std::cerr <<
"\t - computes the successive rational approximation of this number, up to a precision of 1e-14."
<< std::endl;
68
}
69
73
int
main
(
int
argc,
char
** argv )
74
{
75
if
( argc < 2 )
76
{
77
usage
( argc, argv );
78
return
1;
79
}
80
82
typedef
DGtal::int64_t
Integer
;
83
typedef
DGtal::int64_t
Quotient;
84
typedef
LighterSternBrocot<Integer, Quotient, StdMapRebinder>
SB;
// the type of the Stern-Brocot tree
85
typedef
SB::Fraction Fraction;
// the type for fractions
86
typedef
std::back_insert_iterator< Fraction > OutputIterator;
88
90
long
double
epsilon = 1e-14;
91
long
double
number0 = strtold( argv[ 1 ], 0 );
92
long
double
number = number0;
93
ASSERT( number >= 0.0 );
94
Fraction f;
95
OutputIterator itback = std::back_inserter( f );
96
Quotient i = 0;
97
while
(
true
)
98
{
99
long
double
int_part = floorl( number );
100
Quotient u =
NumberTraits<long double>::castToInt64_t
( int_part );
101
*itback++ = std::make_pair( u, i++ );
102
long
double
approx =
103
( (
long
double)
NumberTraits<Integer>::castToDouble
( f.p() ) )
104
/ ( (
long
double
)
NumberTraits<Integer>::castToDouble
( f.q() ) );
105
std::cout <<
"z = "
<< f.p() <<
" / "
<< f.q()
106
<<
" =~ "
<< std::setprecision( 16 ) << approx << std::endl;
107
number -= int_part;
108
if
( ( (number0 - epsilon ) < approx )
109
&& ( approx < (number0 + epsilon ) ) )
break
;
110
number = 1.0 / number;
111
}
112
std::cout <<
"z = "
<< f.p() <<
" / "
<< f.q() << std::endl;
114
return
0;
115
}
DGtal::LighterSternBrocot
Aim: The Stern-Brocot tree is the tree of irreducible fractions. This class allows to construct it pr...
Definition
LighterSternBrocot.h:109
Integer
Point::Coordinate Integer
Definition
examplePlaneProbingParallelepipedEstimator.cpp:44
DGtal
DGtal is the top-level namespace which contains all DGtal functions and types.
Definition
ClosedIntegerHalfPlane.h:49
DGtal::int64_t
std::int64_t int64_t
signed 94-bit integer.
Definition
BasicTypes.h:73
DGtal::NumberTraits
Aim: The traits class for all models of Cinteger.
Definition
NumberTraits.h:562
main
int main(int, char **)
Definition
testIntegerComputer.cpp:331
usage
void usage(int, char **argv)
Definition
testPolynomial.cpp:58
examples
arithmetic
approximation.cpp
Generated on
for DGtal by
1.18.0