Why do I obtain different results when using the SINGLE function in MATLAB?
1 view (last 30 days)
Show older comments
When I execute the following function with WHOS uncommented in the FOR loop, I get the answer as 1.1921e-07. However when I execute the same function with WHOS commented in the FOR loop, I get a different answer.
function foo=calceps()
foo = single(1.0);
while (1.0 + foo/2.0) > 1
foo = foo / 2.0;
%whos
end
without WHOS the result received is:
ans =
2.2204e-16
with WHOS the result received is
ans =
1.1921e-07
Accepted Answer
MathWorks Support Team
on 27 Jun 2009
Internally the JIT (and accelerator) stores all scalar values in double precision even if they have single type. Also, on x86 platforms the JIT (and accelerator) stores all temporaries in double precision and does all mathematics in double precision arithmetic. The interpreter does all mathematics in double precision but keeps all temporaries in single precision. The only time the JIT stores in single precision is when there is an explicit assignment to a single value or when it needs to transfer control back to the interpreter.
In this case, when there is no 'whos' in the loop, the JIT is able to execute the entire loop without falling back to the interpreter. When the 'whos' is inserted into the loop then the JIT can only operate on the body (i.e. foo = foo / 2.0). The rest is done in the interpreter which stores all values in single precision.
To work around this issue, turn off code acceleration to obtain consistent results in both cases.
feature('accel',0)
0 Comments
More Answers (0)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!