DGtal  0.6.devel
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Groups Pages
approximation.cpp
1 
14 
15 
16 #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 Fraction::ConstIterator ConstIterator; // the iterator type for visiting quotients
53  typedef Fraction::Value Value; // the value of the iterator, a pair (quotient,depth).
54  typedef std::back_insert_iterator< Fraction > OutputIterator;
56 
58  long double epsilon = 1e-14;
59  long double number0 = strtold( argv[ 1 ], 0 );
60  long double number = number0;
61  ASSERT( number >= 0.0 );
62  Fraction f;
63  OutputIterator itback = std::back_inserter( f );
64  Quotient i = 0;
65  while ( true )
66  {
67  long double int_part = floorl( number );
68  Quotient u = NumberTraits<long double>::castToInt64_t( int_part );
69  *itback++ = std::make_pair( u, i++ );
70  long double approx =
71  ( (long double) NumberTraits<Integer>::castToDouble( f.p() ) )
72  / ( (long double) NumberTraits<Integer>::castToDouble( f.q() ) );
73  std::cout << "z = " << f.p() << " / " << f.q()
74  << " =~ " << setprecision( 16 ) << approx << std::endl;
75  number -= int_part;
76  if ( ( (number0 - epsilon ) < approx )
77  && ( approx < (number0 + epsilon ) ) ) break;
78  number = 1.0 / number;
79  }
80  std::cout << "z = " << f.p() << " / " << f.q() << std::endl;
82  return 0;
83 }
84