Converting a decimal string to mpq_t
Paul Zimmermann
Paul.Zimmermann at inria.fr
Wed Apr 30 17:30:30 CEST 2025
Hi,
this seems an easy question, with not an easy answer.
If your input has no (decimal) exponent, you can shift the decimal point to
the right, then you have an integer, use mpq_set_str, and divide by the
appropriate power of 10. If your input has an exponent, you have to multiply
by 10^e. But this needs to write your own parser.
Another algorithm is the following, with no parser to write, but you need
GNU MPFR.
Assume your input has precision at most p decimal digits. Convert your input
to a P-bit binary number with rounding to nearest using mpfr_set_str, such
that P >= 1 + p*log(10)/log(2). Then convert back to a p-digit decimal
string using mpfr_get_str (still with rounding to nearest). The condition
on P ensures you get the same value as initially. You can then convert this
string (mpfr_get_str yields an integer mantissa and an exponent) using
mpq_set_str for example (and dealing with the exponent as above).
Hope this helps,
Paul
> From: Anders Andersson <pipatron at gmail.com>
> Date: Mon, 28 Apr 2025 21:54:34 +0200
>
> Good evening! I wanted to convert a simple decimal string such as
> "0.1" to an mpq_t but I can't find a way to do it even though an mpq_t
> should be able to represent every such number exactly in every base,
> except possibly NaN and Inf.
>
> Do I have to write my own parser or do you have any ideas? Have I
> missed something obvious?
>
> If I manage to summon the strength to write such a function, would it
> be a good idea to extend mpq_set_str to handle floating point input?
>
>
> // Anders
> _______________________________________________
> gmp-discuss mailing list
> gmp-discuss at gmplib.org
> https://gmplib.org/mailman/listinfo/gmp-discuss
>
More information about the gmp-discuss
mailing list