I am using matlab. I have a function f(x) and I want to apply f(x) to a set of values. So I wrote 2 codes. The first code is a simple for loop. At one point x0, inside this for loop, I find that f(x0)=1.0000 and then I use f(x0)-1=-4.7684e-07.
My second code is using arrayfun on f(x). And at the same input value x0, I found that the results is 1.0000 but arrayfun(f,x0)-1=4.7684e-07!
This error 4.7684e-07 looks tiny. But the for loop gives me a number below 1 and the arrayfun gives me a number above 1. This is really a big difference in my work, as my subsequent computations largely hinges on whether this number is below 1 or above 1, as this number is supposed to be a probability.
Now my question is: why arrayfun has such problem? There is no random numbers in my code, why arrayfun generates a different result than for loop? which one should I trust? Is there a way to avoid this kind of precision problem? Note that in this code, all of my variables are in single type. Is this causing the problem?