Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is mpfr_printf different than printf for hex float (%a conversion specifier)?

I'm comparing values from regular floating point arithmetic and using a high-precision MPFR number as a baseline. When printing, I'm confused why the following code is output different.

The MPFR documentation says the output specifiers are

‘a’ ‘A’ hex float, C99 style"

So I would assume it prints the same as printf. However, this is not the case:

#include <boost/multiprecision/mpfr.hpp>

#include <mpfr.h>

using namespace boost::multiprecision;

int main (int argc, char* argv[])
{
    double               a = 254.5;
    mpfr_float_1000 mpfr_a = 254.5;

    mpfr_t t;
    mpfr_init2(t, 3324); // 1000 decimal precision
    mpfr_set_d(t, a, MPFR_RNDN);

    printf("double:\t%a\n", a);
    mpfr_printf("mpfr_t:\t%RNa\n", t);
    mpfr_printf("boost:\t%RNa\n", mpfr_a);
}

Gives output:

double: 0x1.fdp+7
mpfr_t: 0xf.e8p+4
boost:  0xf.e8p+4

It's not a huge deal because sscanf parses both of them as the same value, but I couldn't locate any documentation explaining why they are different.

Which one is canonical?

like image 868
sdpoll Avatar asked Apr 13 '26 17:04

sdpoll


1 Answers

There is no canonical form. The C standard does not regulate the first digit except that it must be non-zero for normal numbers. C 2018 7.21.6.1 8 says, of the a and A conversion specifiers:

A double argument representing a floating-point number is converted in the style [-]0xh.hhhhp±d, where there is one hexadecimal digit (which is nonzero if the argument is a normalized floating-point number and is otherwise unspecified) before the decimal-point character and the number of hexadecimal digits after it is equal to the precision;…

like image 195
Eric Postpischil Avatar answered Apr 15 '26 08:04

Eric Postpischil