home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 2 / Apprentice-Release2.iso / Source Code / C++ / Libraries / continued_fraction / continued_fraction.cp < prev    next >
Encoding:
Text File  |  1994-11-08  |  1.4 KB  |  75 lines  |  [TEXT/KAHL]

  1. #include <math.h>
  2.  
  3. #include <iostream.h>
  4. #include <iomanip.h>
  5.  
  6. #include "continued_fraction.h"
  7.  
  8. continued_fraction::continued_fraction( long double number) : x( number)
  9. {
  10.     restart();
  11. }
  12.  
  13. void continued_fraction::restart()
  14. {
  15.     rest = x;
  16.  
  17.     p_2 = 0;
  18.     p_1 = 1;
  19.     q_2 = 1;
  20.     q_1 = 0;
  21. }
  22.  
  23. int continued_fraction::step( int numsteps)
  24. {
  25.     int num_steps_taken = 0;
  26.     
  27.     while( (num_steps_taken < numsteps) && (step_once() == true))
  28.     {
  29.         num_steps_taken += 1;
  30.     }
  31.     compute_deriveds();
  32.     return num_steps_taken;
  33. }
  34.  
  35. Boolean continued_fraction::step_once()
  36. {
  37.     if( rest != 0.0)
  38.     {
  39.         const unsigned long a_k = (const unsigned long)floor( rest);
  40.         const unsigned long p_0 = a_k * p_1 + p_2;
  41.         const unsigned long q_0 = a_k * q_1 + q_2;
  42.     
  43.         rest = 1.0 / (rest - (long double)a_k);
  44.         p_2 = p_1;
  45.         q_2 = q_1;
  46.         p_1 = p_0;
  47.         q_1 = q_0;
  48.     }
  49.     return (rest != 0.0);
  50. }
  51.  
  52. long double continued_fraction::step_till_relerror( long double max_relerror)
  53. {
  54.     while( (relerror > max_relerror) && step()){}
  55.     return relerror;
  56. }
  57.  
  58. long double continued_fraction::step_till_error( long double max_error)
  59. {
  60.     while( (error > max_error) && step()){}
  61.     return error;
  62. }
  63.  
  64. ostream &operator<<( ostream &os, const continued_fraction &it)
  65. {
  66.     static const int longWidth   =  9;
  67.     static const int doubleWidth = 10;
  68.     os
  69.         << setw( longWidth) << it.p_1 << " / " << setw( longWidth) << it.q_1
  70.         << " = " << setw( doubleWidth) << it.fract
  71.         << " (error " << it.error << "; " << it.relerror << " relative)";
  72.     
  73.     return os;
  74. }
  75.