views:

50

answers:

2

When using fprintf to convert floats to text in a decimal representation, the output is a series of decimal digits (potentially beginning with 0).
How does this representation work?

>>fprintf('%tu\n',pi)
>>1078530011
>>fprintf('%bu\n',pi)
>>04614256656552045848

Apologies if this is very trivial; I can't find an answer elsewhere, in part because searches are swamped by the various decimal data types available.

Note that the %t and %b flags are two of the differences from C's fprintf(). According to the documentation, it prints a float or double respectively "rather than an unsigned integer." o, x and u switches between octal, hex and decimal.

+2  A: 

This representation is the binary IEEE 754 floating point representation of the number, printed as an unsigned integer.

The IEEE 754 Converter website tells us that the IEEE 754 single-precision representation of Pi (approximately 3.1415927) is 40490FDB hexadecimal, which is 1078530011 decimal (the number that you saw printed). The '%bu' format specifier works similarly but outputs the double-precision representation.

The purpose of these format specifiers is to allow you to store a bit-exact representation of a floating-point value to a text file. The alternative approach of printing the floating-point value in human-readable form requires a lot of care if you want to guarantee bit-exact storage, and there might be some edge cases (denormalized values...?) that you won't be able to store precisely at all.

Martin B
+1  A: 

If you were to print the number as hexadecimals:

>> fprintf('%bx\n', pi)
    400921fb54442d18

>> fprintf('%tx\n', single(pi))
    40490fdb

then the formatters '%bx' and '%tx' are simply equivalent to using NUM2HEX:

>> num2hex( pi )
    400921fb54442d18

>> num2hex( single(pi) )
    40490fdb

Another way is to simply set the default output format to hexadecimals using:

>> format hex
>> pi
   400921fb54442d18
>> single(pi)
   40490fdb

On a related note, there was a recent article by @Loren: "How Many Digits to Write?" where they try to find how many decimal digits you need to write in order to retain the number's full precision when re-read in MATLAB.

Amro