[prev in list] [next in list] [prev in thread] [next in thread] 

List:       kde-devel
Subject:    Re: display decimal as normal fraction
From:       Joachim Eibl <joachim.eibl () gmx ! de>
Date:       2004-05-22 12:18:24
Message-ID: 200405221418.24988.joachim.eibl () gmx ! de
[Download RAW message or body]

On Monday 03 May 2004 18:31, M2George wrote:
> Is there any way that I could take a value from a variable and then display
> that variable as a normal fraction.
>
> ie: 3.142857143 as 22/7 only on top of each other.

Just for fun: A little implementation that searches for the best match, given 
a certain maximum divisor.

// Output:
// # findbestfraction 3.1428571 100
// 3.14286 = 22/7 + (-4.28571e-08)

#include <math.h>
#include <iostream>

int main(int argc, char** argv)
{
   if(argc==3)
   {
      double dFraction = atof(argv[1]);
      int maxDivisor = atoi(argv[2]);
      
      int bestI = 0;
      double dBestError = 0;
      
      int i;
      for( i=1; i<maxDivisor; ++i )
      {
         double dResult = dFraction * i;
	 // Relative error (for nicer results)
	 double dError = fabs( (floor( dResult + 0.5 ) - dResult) );
	 
         //std::cout << i << ":" << dError << std::endl;      
	 
	 if( dError<dBestError || bestI==0 )
	 {
	    bestI = i;
	    dBestError = dError;
	 }
      }
      
      std::cout << dFraction << " = "
                << (int)floor( dFraction * bestI + 0.5) << "/" << bestI 
		<< " + (" << dFraction - floor( dFraction * bestI + 0.5) / bestI  
		<< ")" << std::endl;      
   }
   return 0;
}

Of course this can get slow for big maxDivisors.

Joachim
 
>> Visit http://mail.kde.org/mailman/listinfo/kde-devel#unsub to unsubscribe <<
[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic