guitar-player

farey_seq.cpp

Aug 9th, 2012
34
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.45 KB | None | 0 0
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <cmath>
  4. #include <stdlib.h>
  5. #include <stdio.h>
  6. #include <math.h>
  7. #include <cstdlib>
  8.  
  9. using namespace std;
  10.  
  11. pair<long int,long int > farey(const __float80 &x, const long int &N){
  12.     pair < long int , long int >  p;
  13.     __float80 media;
  14.     long int a = 0 ,b = 1,c = 1,d = 1;
  15.     while ( b <= N && d <= N ){
  16.         media = (__float80(a+c)/(b+d));
  17.         //cout << media << endl;
  18.         if ( x == media ){
  19.             if ((b+d) <= N){
  20.             return make_pair(a+c,b+d);
  21.         }
  22.             else if( d > b ){
  23.                 return make_pair(c,d);
  24.             }
  25.             else{
  26.                 return make_pair(a,b);
  27.             }
  28.         }
  29.         else if( x > media ){
  30.             a = a+c;
  31.             b = b+d;
  32.         }
  33.         else {
  34.             c = c+a;
  35.             d = b+d;
  36.         }
  37.     }
  38.     if ( b >  N ){
  39.         return make_pair(c,d);
  40.     }else{
  41.         return make_pair(a,b);
  42.     }
  43. }
  44.  
  45. int main(int argc , char *argv[]){
  46.    
  47.     if (argc <= 1 ) {
  48.         cout << "Necesita un argumento decimal entre 0 y 1" << endl;
  49.         exit (1);
  50.     }
  51.     __float80 pp = atof(argv[1]);
  52.     pair<long int,long int> p1 ,p2;
  53.     __float80 rate = 1;
  54.     __float80 prec = 1;
  55.     __float80 decimal = pp;
  56.     __float80 real_precision = 1E-12;
  57.     long int j = 10000;
  58.    
  59.     while( prec > real_precision ){
  60.         j   += 10000;
  61.         p1   = farey(decimal,j);
  62.         rate = __float80(double(p1.first))/(p1.second);
  63.         prec = abs(decimal-rate);
  64.     }
  65.    
  66.     cout << "la fracion es : ";
  67.     cout << setw(6) << setprecision(15) << p1.first <<  "/" << p1.second ;
  68.     cout <<"   "    << setw(9) << rate <<" "<< setw(12) << prec << endl;
  69.     return 0;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment