Number to String Conversion Inaccuracy

4 次查看(过去 30 天)
I have a case where I have a whole number that is 19 digits long (1000000000000000001). If you pass this into num2str or sprintf the results differ from the original number. Now I know the result is a string and the data types are different but their representations should be identical. Below is an example.
A = 1000000000000000001;
sprintf('%0.20g', A);
Results:
ans =
'1000000000000000000'
If you change A to equal 10000000000000000002 the results are still the same. These aren't the only values that are subjected to this problem. Every number I have tried with 19 digits or more has this problem.
  2 个评论
Ive J
Ive J 2021-1-25
编辑:Ive J 2021-1-25
I don't think it's an issue with num2str itself. Even if you compare A to 1e18, they're equal for MATLAB
A = 1000000000000000001;
A == 1e18
ans =
logical
1
VPI Toolbox may be of help.

请先登录,再进行评论。

回答(1 个)

Jan
Jan 2021-1-25
编辑:Jan 2021-1-25
Matlab uses the default type double, which is defined by the IEEE 754 standard. This type is implemented in the CPU hardware also. Doubles store about 16 decimal digits and an exponent in 64 bits.
This means, that 19 decimal digits cannot be stored accurately in a double precision variable. It is not a problem of the conversion to a string, but
A = 1000000000000000001;
crops the rightmost digits already.
Another example, where this matters:
1e17 + 1 - 1e17 % 0
This replies 0 instead of the mathematical result 1. Reordering the terms produces a different result:
1e17 - 1e17 + 1 % 1
These effects have to be considered for computations with limited precision. The corresponding techniques belong to the field of numerical maths.

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

产品


版本

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by