strange behavior in reading in rational fractions

Nathan Moore nmoore at physics.umn.edu
Tue Apr 6 18:28:27 CEST 2004


Hello all,

The GMP idea seems like a really neat concept. Right now I'm writing a 
test program for my research work which reads in fractions from a test 
file,
  - - -
	nmoore% cat fractions.txt
	6,1/2,1/32,1/23,1/24,2/23,-3/1,
  - - -
The simple c++ program reads in the values from file, converts them to 
double and then prints out again.  I use the following code (main 
function listed).  The main problem is that section which reads in from 
file,

	mpq_inp_str(f_in[i], DATA, 10);
	fscanf(DATA,",");

requires the extra fscanf to hop over the comma.  This seems strange, 
but I guess I'll accept it if I have to.  Is there an easier way? The 
output without the fscanf is incorrect,
- - - -
	6 records in file
	fraction[0] =   0.5000000000000000000000000
	fraction[1] =   0.0000000000000000000000000
	fraction[2] =   0.0312500000000000000000000
	fraction[3] =   0.0000000000000000000000000
	fraction[4] =   0.0434782608695652161845402
	fraction[5] =   0.0000000000000000000000000
- - - -
output with fscanf is the proper result.
- - - -
	6 records in file
	fraction[0] =   0.5000000000000000000000000
	fraction[1] =   0.0312500000000000000000000
	fraction[2] =   0.0434782608695652161845402
	fraction[3] =   0.0416666666666666643537020
	fraction[4] =   0.0869565217391304323690804
	fraction[5] =  -3.0000000000000000000000000
- - - -

code follows:
- - - -
int main() {
         FILE * DATA;
         DATA=fopen("fractions.txt","r");
         double var;
         int i, num_records;

         // read in the number of records
         fscanf(DATA,"%d,",&num_records);
         printf("\n%d records in file\n",num_records);

         // declare rational number, "f_in"
         mpq_t f_in[num_records];

         // initialize the variable
         // mpq_init (mpq_t dest_rational)
         for(i=0;i<num_records;i++) { mpq_init(f_in[i]); }

         for(i=0;i<num_records;i++) {
                 // read the variable in from file
                 // mpq_inp_str (mpq_t rop, FILE *stream, int base)
                 mpq_inp_str(f_in[i], DATA, 10);
                 fscanf(DATA,",");
         }


         for(i=0;i<num_records;i++) {
                 // make variable into proper form
                 mpq_canonicalize(f_in[i]);

                 // convert variable to double format and print
                 var = mpq_get_d(f_in[i]);
                 printf("fraction[%d] =%30.25lf\n",i,var);
         }

         for(i=0;i<num_records;i++) { mpq_clear(f_in[i]); }

         fclose(DATA);
         return 1;
}
- - - -



More information about the gmp-discuss mailing list