If this code weren’t so mature I’d think GMP may be buggy here.
The doc here https://gmplib.org/manual/Assigning-Floats says:
Function: int mpf_set_str (mpf_t rop, const char *str, int base)
Set the value of rop from the string in str. The string is of the form ‘M@N’ or, if the base is 10 or less, alternatively ‘MeN’. ‘M’ is the mantissa and ‘N’ is the exponent. The mantissa is always in the specified base. The exponent is either in the specified base or, if base is negative, in decimal. The decimal point expected is taken from the current locale, on systems providing localeconv.
I am trying to write something like 1.23456789 x 10^-5 as 123456789e-5.
So I wrote code to spit out the mantissa and exponent, then I fed it back in to mpf_set_str() and I should get the same number, but I get a different number!
Am I doing something wrong?
void test_mpf_str(void)
{
char real_x[2048];
long exp;
mpf_t x_coord_mpf;
mpf_init(x_coord_mpf);
mpf_set_str(x_coord_mpf, "0.00000123456789", 10);
gmp_printf("INPUT: %.Ffn", x_coord_mpf);
mpf_get_str(real_x, &exp, 10, 2048-2, x_coord_mpf);
printf("REAL_X: %s EXP: %ldn", real_x, exp);
sprintf(real_x, "%se%ld", real_x, exp);
printf("ASSIGNED REAL_X: %sn", real_x);
//all these below are wrong!
mpf_set_str(x_coord_mpf, real_x, 10);
gmp_printf("NEW INPUT: %.Ffn", x_coord_mpf);
mpf_get_str(real_x, &exp, 10, 2048-2, x_coord_mpf);
printf("NEW REAL_X: %s EXP: %ldn", real_x, exp);
mpf_clear(x_coord_mpf);
}
And output:
INPUT: 0.00000123456789
REAL_X: 123456789 EXP: -5
ASSIGNED REAL_X: 123456789e-5
NEW INPUT: 1234.56789
NEW REAL_X: 123456789 EXP: 4
I think I am right to expect that the new values should be the same as the old values. I’m not so sure why the mantissa looks right but the exp is very wrong. I also tried using ‘@’ instead of ‘e’.
I’ve installed GMP 6.3.0 via homebrew on macOS Sonoma 14.5 FYI and using it in Xcode 15.4.