Syntax: var<1d-4

5 vues (au cours des 30 derniers jours)
Pranav Krishnan
Pranav Krishnan le 29 Mai 2020
Modifié(e) : dpb le 30 Mai 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.

Réponse acceptée

dpb
dpb le 29 Mai 2020
Modifié(e) : dpb le 30 Mai 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.

Plus de réponses (0)

Catégories

En savoir plus sur Fortran with MATLAB dans Help Center et File Exchange

Produits


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by