Where do all these digits come from?

3 views (last 30 days)
Hello
I know Matlab stores 52 bits which roughly means 16 decimal places. But if I ask for 40 digits of pi, I get 40 digits, the last ones all wrong
>> fprintf('%41.40f\n',pi)
3.141 5926 5358 9793 1159979634685441851615906
>> vpa(pi,41)
3.141 5926 5358 9793 2384626433832795028841972
Well, I did not expect correct digits, but I would like to know why these garbage digits.
Thanks,
Mariano

Accepted Answer

Walter Roberson
Walter Roberson on 10 Feb 2020
3.141592653589793115997963468544185161590576171875
is what is stored for pi -- just a little longer than you happened to display.
If you are using MATLAB on MS Windows, then the digits you see output after the 16th are either 0 or garbage that happens to be randomly in the buffer. For MATLAB on MS Windows, to see numbers accurately, you should use num2strexact from the File Exchange.
If you are using MATLAB on Linux, then historically after some point (I no longer recall the length), fprintf() would produce zeros instead of correct digits.
If you are using MATLAB on Mac, then it has always produced all of the correct digits.
The digits you see are the base 10 representation of the binary value that is stored.
>> num2hex(pi)
ans =
'400921fb54442d18'
>> pi-hex2num('400921fb54442d17')
ans =
4.44089209850063e-16
>> hex2num('400921fb54442d19')-pi
ans =
4.44089209850063e-16
>> sym(hex2num('400921fb54442d18'),'d')
ans =
3.141592653589793115997963468544185161590576171875
>> sym(hex2num('400921fb54442d19'),'d')
ans =
3.141592653589793560087173318606801331043243408203125
>> vpa(sym(pi))
ans =
3.141592653589793238462643383279502884197169399375105820974944592307816406286209
Comparing, you can see that the '400921fb54442d18' version is a little too low, and the '400921fb54442d19' version is a little too high. The value that was used, '400921fb54442d18', was chosen as being closer to the infinitely precise version of pi than the next number '400921fb54442d19' is.

More Answers (0)

Categories

Find more on Debugging and Analysis in Help Center and File Exchange

Products


Release

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!