MATLAB Answers

Syntax: var<1d-4

6 views (last 30 days)
Pranav Krishnan
Pranav Krishnan on 29 May 2020
Edited: dpb on 30 May 2020
In the body of a program I'm using as reference, this if statement is provided:
dp=max(max(abs(phi1a-phi1)));
if(~(dp>0) & ~(dp<0) ) disp('NaN'); return; end
if(dp<1d-4) break; end % THIS LINE
where variable 'dp' is defined as so, and phi1a and ph1 are NxN matrices. What I don't understand is the second if condition - does this mean 10^-4? If so why is 'd' used, instead of 'e' as is usually.

  0 Comments

Sign in to comment.

Accepted Answer

dpb
dpb on 29 May 2020
Edited: dpb on 30 May 2020
dp=max(max(abs(phi1a-phi1)));
if(~(dp>0) & ~(dp<0) ) disp('NaN'); return; end
if(dp<1d-4) break; end % THIS LINE
could be written as
dp=max(abs(phi1a(:)-phi1(:))); % pre-R2018b
dp=max(abs(phi1a-phi1),[],'all'); % R2018b and later
if isnan(dp), disp('NaN'); return; end
if(dp<1E-4), break; end
'd' for the exponent letter is MATLAB carryover from Fortran syntax; "e" is single precision, "d" is double. MATLAB uses default double precision for all numeric values unless specifically cast to something else and "e" is interpreted the same as "d". Upper/lower case are also allowable and mean the same; I think written as a literal constant the uppercase is more legible but it's personal taste.
In Fortran, however, the two forms are different -- 1.0E-4 is a single precision value; 1.0D-4 is double precision. For values which can be represented identically as the above, the end result on assignment is the same; numbers which are not, however, like 0.2, are in fact different if stored in a double precision variable. The D form will have full precision; the E form will be a single precision result zero-extended to double; it will still have the single precision precision stored in the double variable.
However, unlike Fortran, MATLAB and C i/o does not support the "dD" form for double precision constants other than as literal constants in source code as written above.
>> sscanf('1E-4','%f')
ans =
1.0000e-04
>> sscanf('1D-4','%f')
ans =
1
>> sscanf('1D-4','%e')
ans =
1
>> sscanf('1e-4','%e')
ans =
1.0000e-04
>>
NB: the constant written with D fails with either floating point format string.
The writer of the above code would appear to have had a FORTRAN background and to not be terribly familiar with MATLAB syntax.
ADDENDUM: Or perhaps the code was translated from old FORTRAN, maybe, and just implemented verbatim on a line-by-line basis.

  0 Comments

Sign in to comment.

More Answers (0)

Products


Release

R2020a

Translated by