Filter löschen
Filter löschen

Is there a way to retain the precision of the zero?

11 Ansichten (letzte 30 Tage)
h s
h s am 26 Feb. 2017
Bearbeitet: Stephen23 am 26 Feb. 2017
I have a large string array with 0.000000, but when I convert it to a matrix through 'num2str' it is converted into 0. I have tried format long, etc. but it only affects the numbers other than zero.
  1 Kommentar
Stephen23
Stephen23 am 26 Feb. 2017
Bearbeitet: Stephen23 am 26 Feb. 2017
"I have tried format long, etc. but it only affects the numbers other than zero"
Changing the format makes absolutely no difference to the precision of the variable stored in memory, only to how they are displayed. Here is an example:
>> X = 2.009
X =
2.009
>> format bank
>> X
X =
2.01
>> X*100
ans =
200.90
The last step above shows that format bank does not change the precision of the stored variable whatsoever: it still retains all digits of precision that it had when it was defined.
Zero is stored with exactly the same precision as any other values of the same class. You cannot change its stored precision for one class, only its displayed precision.

Melden Sie sich an, um zu kommentieren.

Antworten (2)

Star Strider
Star Strider am 26 Feb. 2017
If the string representation is just '0.000000', the str2num result double(0) is nnumerically as precise as it’s going to get! It has the full precision internally.

Walter Roberson
Walter Roberson am 26 Feb. 2017
Assuming that numbers are not in scientific format,
num_decimals = cellfun(@length, regexprep(YourCell, '^\d*\.', ''));
as_num = str2double(YourCell);
Now, as_num is the numeric value of YourCell, and num_decimals is the number of digits after the decimal point associated with each entry.
If at some point you need to print them back out with the original number of decimal places, then
delimiter = ' ';
fmt = [repmat( ['%.*f', delimiter], 1, size(as_num,2)-1), '%.*f\n'];
temp = [ num2cell(num_decimals(:)) .'; num2cell(as_num(:)) .'];
fprintf( fmt, temp{:} )
Remember, the number of 0's printed out is a matter of display, not of what is actually stored. What is actually stored is binary rather than decimal.

Kategorien

Mehr zu Numeric Types finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by