开发者

Float to text behavior of MATLAB's fprintf()

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 开发者_如何学JAVAtypes 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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜