# problem when converting from double

Will Galway galway at math.uiuc.edu
Fri Jan 28 17:23:06 CET 2005

```You say that you get junk when you set g=0.333, but what junk do you
get?  With a quick glance at your code, it looks correct to me, so I'd
guess that in the "junk case" the ratio of your numerator to your
denominator is roughly 0.333.  I'd be AMAZED if the numerator==333,
denominator==1000, or numerator=1, denominator==3, or anything so
pretty.  Remember that "0.333" is going to be some binary
approximation to 333/1000, and that 333/1000 must have an infinite
binary expansion to be exact.

-- Regards, Will
( mailto:galway at math.uiuc.edu  http://www.math.uiuc.edu/~galway )

On Friday January 28, 2005 at 10:16:57, Thomas Abraham wrote:
> hi,
>
> I am a beginner with GMP so this may sound stupid :
>
> I am trying to convert a double type to rational and then find the
> numerator and denominator integers. so i do
> *******************************
> mpq_t val;
> double g;
> mpz_t num,den;
> signed long int valnum, valden;
>
> mpq_init(val);mpz_init(num);mpz_init(den);
> g=0.333;
> mpq_set_d(val,g);
>
> mpq_get_num(num,val);
> mpq_get_den(den,val);
>
> valnum=mpz_get_si(num);
> valden=mpz_get_si(den);
>
> *******************************************
>
> now if I set g=0.5 , I get valnum=1,valden=2 .
> if i set g=0.333 , i get junk.
> if i use mpz_fits_slong_p(num) , it gives me zero in the second case.
>
> Is there a problem with my compiler? Is my code totally wrong? Is
> there an easier way to do this? I looked at the manual about 10 times
> but could not find out how to get the numerator and denominator for
> certain double values as mentioned above.
>
> any suggestions would be greatly appreciated
>
> thanks
>
> Tom
>
> thomaskabraham at gmail.com
> _______________________________________________
> gmp-discuss mailing list
> gmp-discuss at swox.com
> https://gmplib.org/mailman/listinfo/gmp-discuss
```

More information about the gmp-discuss mailing list