Converting a decimal string to mpq_t
American Citizen
website.reader3 at gmail.com
Wed Apr 30 01:21:31 CEST 2025
I wrote a program to see for myself, but my executable seems to have
failed too.
#include <stdio.h>
#include <gmp.h>
int main() {
const int base = 10;
const mp_bitcnt_t prec = 5;
mpq_t Q;
mpq_init(Q);
printf("initial Q = ");
mpq_out_str(NULL,base,Q);
printf("\n");
mpf_t F;
mpf_init2(F,prec);
const char* S = "0.1";
printf("S = %s\n",S);
mpf_set_str(F,S,base);
size_t digits = 5;
printf("F = ");
mpf_out_str(NULL,base,digits,F);
printf("\n");
mpq_set_f(Q,F);
printf("Q = ");
mpq_out_str(NULL,base,Q);
printf("\n");
mpq_clear(Q);
mpf_clear(F);
return (0);
}
Output:
initial Q = 0
S = 0.1
F = 0.1e0
Q =
627710173538668076383578942320766641610235544446403451289/6277101735386680763835789423207666416102355444464034512896
On 4/28/25 22:30, Anders Andersson wrote:
> Neither will work, 0.1 is even an example in the mpf documentation:
> "The mantissa is stored in binary. One consequence of this is that
> decimal fractions like 0.1 cannot be represented exactly"
>
> And as I hinted to in my original message, mpq_set_str does not handle
> floating point strings (according to its manual).
>
> // Anders
>
>
> On Mon, Apr 28, 2025 at 11:34 PM Brett Kuntz <kuntz at shaw.ca> wrote:
>> Use mpf_set_str() to convert the string to an mpf, then use mpq_set_f() to convert the mpf to an mpq. There is also an mpq_get_str() function but I've never used it before so I am not sure if it can handle decimal numbers in base 10. Try out both methods!
>>
>> https://gmplib.org/manual/index
>>
>> -Brett
>>
>>
>>
>>
>> ________________________________
>> From: "Anders Andersson" <pipatron at gmail.com>
>> To: "gmp-discuss" <gmp-discuss at gmplib.org>
>> Sent: Monday, April 28, 2025 2:54:34 PM
>> Subject: Converting a decimal string to mpq_t
>>
>> 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
> _______________________________________________
> gmp-discuss mailing list
> gmp-discuss at gmplib.org
> https://gmplib.org/mailman/listinfo/gmp-discuss
More information about the gmp-discuss
mailing list