core/vnl/vnl_rational.cxx

Go to the documentation of this file.
00001 // This is core/vnl/vnl_rational.cxx
00002 #include "vnl_rational.h"
00003 //:
00004 // \file
00005 
00006 //: Creates a rational from a double.
00007 //  This is done by computing the continued fraction approximation for d.
00008 vnl_rational::vnl_rational(double d)
00009 {
00010   bool sign = d<0;
00011   if (sign) d = -d;
00012 
00013   // Continued fraction approximation of abs(d): recursively determined
00014   long den=0L, num=1L, prev_den=1L, prev_num=0L;
00015 
00016   while (d*num < 1e9 && d*den < 1e9) {
00017     long a = (long)d; // integral part of d
00018     d -= a; // certainly >= 0
00019     long temp = num; num = a*num + prev_num; prev_num = temp;
00020          temp = den; den = a*den + prev_den; prev_den = temp;
00021     if (d < 1e-6) break;
00022     d = 1/d;
00023   }
00024   num_ = num; den_ = den;
00025   if (sign) num_ = -num_;
00026   // no need to normalize() since prev_num and prev_den have guaranteed a gcd=1
00027 }

Generated on Sat Nov 22 05:06:22 2008 for core/vnl by  doxygen 1.5.1