DGtal  0.9.3beta
approximation.cpp
1 
14 #include <cstdlib>
17 #include <cmath>
18 #include <iostream>
19 #include <iomanip>
20 #include "DGtal/arithmetic/LighterSternBrocot.h"
21 #include "DGtal/base/StdRebinders.h"
23 
25 
26 using namespace DGtal;
27 
29 
30 void usage( int, char** argv )
31 {
32  std::cerr << "Usage: " << argv[ 0 ] << " <floating point number>" << std::endl;
33  std::cerr << "\t - computes the successive rational approximation of this number, up to a precision of 1e-14." << std::endl;
34 }
35 
39 int main( int argc, char** argv )
40 {
41  if ( argc < 2 )
42  {
43  usage( argc, argv );
44  return 1;
45  }
46 
48  typedef DGtal::int64_t Integer;
49  typedef DGtal::int64_t Quotient;
50  typedef LighterSternBrocot<Integer, Quotient, StdMapRebinder> SB; // the type of the Stern-Brocot tree
51  typedef SB::Fraction Fraction; // the type for fractions
52  typedef std::back_insert_iterator< Fraction > OutputIterator;
54 
56  long double epsilon = 1e-14;
57  long double number0 = strtold( argv[ 1 ], 0 );
58  long double number = number0;
59  ASSERT( number >= 0.0 );
60  Fraction f;
61  OutputIterator itback = std::back_inserter( f );
62  Quotient i = 0;
63  while ( true )
64  {
65  long double int_part = floorl( number );
66  Quotient u = NumberTraits<long double>::castToInt64_t( int_part );
67  *itback++ = std::make_pair( u, i++ );
68  long double approx =
69  ( (long double) NumberTraits<Integer>::castToDouble( f.p() ) )
70  / ( (long double) NumberTraits<Integer>::castToDouble( f.q() ) );
71  std::cout << "z = " << f.p() << " / " << f.q()
72  << " =~ " << std::setprecision( 16 ) << approx << std::endl;
73  number -= int_part;
74  if ( ( (number0 - epsilon ) < approx )
75  && ( approx < (number0 + epsilon ) ) ) break;
76  number = 1.0 / number;
77  }
78  std::cout << "z = " << f.p() << " / " << f.q() << std::endl;
80  return 0;
81 }
82 
DGtal::int32_t Integer
Definition: StdDefs.h:74
Aim: The traits class for all models of Cinteger.
Definition: NumberTraits.h:69
static DGtal::int64_t castToInt64_t(const T &aT)
Definition: NumberTraits.h:146
DGtal is the top-level namespace which contains all DGtal functions and types.
Aim: The Stern-Brocot tree is the tree of irreducible fractions. This class allows to construct it pr...
boost::int64_t int64_t
signed 94-bit integer.
Definition: BasicTypes.h:74