简体   繁体   中英

What is the difference in floating point numbers in Matlab and Python?

I am importing some numbers into python from a matlab "mat" file version 5 and they have a different precision.

This is the python Code:

output_data = numpy.matlab.loadmat( ( path ), mat_dtype=True )

print(output_data)

Python3 output: -0.0030967733388058967-> 20 numbers or digits
Matlab output:  -0.00309677333880590  -> 18  "        "

Why would python and matlab have different precisions?

Hope the answer in this link helps:

https://ww2.mathworks.cn/matlabcentral/answers/77455-raising-to-the-power-of-large-numbers-is-giving-me-the-wrong-answer

To quote the person who answered the question:

In general, MATLAB uses double-precision, which roughly means that you can expect 16 digits of precision.

Both MATLAB and Python/Numpy use the same floating-point representation by default, 64-bit floats (double precision). How this is stored is dictated by your CPU, not by the program (the program basically gets to choose between 32, 64 and 80 bit floats, which are the representations understood by the CPU in your average PC).

The difference that you see is how the programs choose to display the numbers. The internal representation is identical.

If the difference between these numbers, as displayed, matter to your application, you are doing it wrong . Floating-point computations are imprecise by definition, you cannot count on those last few digits to be meaningful.

I've noticed that Python behaves a little different than those other software packages, incl. Matlab (also SPSS Modeler, Excel). That is it somehow provides 1-2 additional decimals on occasion. For example:

In [53]: import numpy

In [54]: numpy.pi
Out[54]: 3.141592653589793

In [55]: numpy.pi * 10000
Out[55]: 31415.926535897932

In [56]: numpy.pi * 100000
Out[56]: 314159.2653589793

In [57]: len(str(numpy.pi))
Out[57]: 17

while others would stick to 16 "meaningful" digits

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM