MATLAB: Does the logical condition of an IF not work for single precision values

acceleratorifMATLABprecisionsinglewhile

I am using single precision in my custom function, within which I have an IF statement. The conditional expression for my IF statement tests for equality of two single precision numbers.
I expect that when the difference between two single precision numbers is smaller than what is possible for single precision, these numbers should be "equal" as far as the code is concerned. However, I find that this is not always the case, as the following code illustrates:
function ifSingleTest(power)
% ifSingleTest(power)
% Creates delta = single(1/2^power)
% delta should be too small for power >= 24 for single precision.
% However, if "feature accel on", then delta is not too small until power >= 53
% which is the same as for double precision
delta = single(1/2^power) %problem only happens when delta is declared as a single
if single(1+delta) ~= single(1)
disp('single(1+delta) ~= single(1)')
else
disp('delta too small')
end
disp([char(13) 'eps(single(1)) = ' sprintf('%1.15e',(eps(single(1))))])
I have found this problem also for the conditional expression of a WHILE loop.

Best Answer

This is the expected behavior in MATLAB 7.8 (R2009a). The MATLAB JIT-Accelerator doesn't keep any intermediate results in single precision on 32-bit x86 machines. Intermediate values are stored in the x87 hardware registers (which are double precision) and are only stored to memory when an assignment is performed (thus converted to single precision). This can give different results from the interpreter which stores out intermediate results to memory (forcing them to single precision) after each step in a calculation.
There are two workarounds:
1. Disable the JIT using the command "feature scopedaccelenablement off" in the function using single precision math, or
2. Store every intermediate value into a variable.