필터 지우기
필터 지우기

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

조회 수: 16 (최근 30일)
h s
h s 2017년 2월 26일
편집: Stephen23 2017년 2월 26일
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
Stephen23
Stephen23 2017년 2월 26일
편집: Stephen23 2017년 2월 26일
"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.

댓글을 달려면 로그인하십시오.

답변 (2개)

Star Strider
Star Strider 2017년 2월 26일
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 2017년 2월 26일
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.

카테고리

Help CenterFile Exchange에서 Numeric Types에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by