3

I saw the function double frexp (double x, int* exp);, which splits a double into the mantissa (m) and the exponent (e), with a power of 2 (1.m * 2^e). Is there a similar function that returns the value in a power of 10? Something like m * 10^e would be perfect.

Pascal Cuoq
  • 79,187
  • 7
  • 161
  • 281
fc67
  • 409
  • 5
  • 17

1 Answers1

9

The thing about frexp is that if you are using IEEE 754 binary floating-point (or PDP-11 floating-point), it simply reveals the representation of the floating-point value. As such, the decomposition is exact, and it is bijective: you can reconstitute the argument from the significand and exponent you have obtained.

No equivalent reason exists for highlighting a power-of-ten decomposition function. Actually, defining such a function would pose a number of technical hurdles: Not all powers of ten are representable exactly as double: 0.1 and 1023 aren't. For the base-ten-significand part, do you want a value that arrives close to the argument when multiplied by 10e, or by the double-precision approximation of 10e? Some floating-point values may have several equally valid decompositions. Some floating-point values may have no decomposition.

If these accuracy and canonicity aspects do not matter to you, use e = floor(log10(abs(x))) for the base-10-exponent (or ceil for a convention more like the PDP-11-style frexp), and x / pow(10, e) for the base-10-significand. If it matters to you that the significand is between 1 and 10, you had better force this property by clamping.


NOTE: If what you want is convert x to decimal, the problem has been studied in depth. The first step of a correctly rounded conversion to decimal is not to compute a base-ten significand as a floating-point number (not in all cases anyway; for some inputs this can be an acceptable shortcut) because in the general case, this step would introduce approximations that are not admissible for a correctly rounded conversion function. For a quick-and-dirty conversion to decimal routine (in the case you have access to log10 but not to sprintf), it may be sufficient.

Community
  • 1
  • 1
Pascal Cuoq
  • 79,187
  • 7
  • 161
  • 281