简体   繁体   English

使用arrayfun时matlab中的精度问题

[英]precision problems in matlab when using arrayfun

I am using matlab.我正在使用 matlab。 I have a function f(x) and I want to apply f(x) to a set of values.我有一个 function f(x) ,我想将f(x)应用于一组值。 So I wrote 2 codes.所以我写了2个代码。 The first code is a simple for loop.第一个代码是一个简单的 for 循环。 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 .在某个点x0 ,在这个 for 循环中,我发现f(x0)=1.0000然后我使用f(x0)-1=-4.7684e-07

My second code is using arrayfun on f(x) .我的第二个代码是在f(x)上使用arrayfun And at the same input value x0 , I found that the results is 1.0000 but arrayfun(f,x0)-1=4.7684e-07 !在相同的输入值x0下,我发现结果是1.0000但是arrayfun(f,x0)-1=4.7684e-07

This error 4.7684e-07 looks tiny.这个错误4.7684e-07看起来很小。 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.但是 for 循环给了我一个低于 1 的数字,而arrayfun给了我一个高于 1 的数字。这对我的工作来说确实是一个很大的不同,因为我后续的计算很大程度上取决于这个数字是低于 1 还是高于 1,因为这个数字应该是概率。

Now my question is: why arrayfun has such problem?现在我的问题是:为什么arrayfun有这样的问题? There is no random numbers in my code, why arrayfun generates a different result than for loop?我的代码中没有随机数,为什么arrayfun生成的结果与 for 循环不同? 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.请注意,在这段代码中,我所有的变量都是single类型的。 Is this causing the problem?这是造成问题的原因吗?

addition and multiplication are not commutative under limited precision, and results depends on the order.加法和乘法在有限精度下不可交换,结果取决于顺序。 For example, adding (a+b+c+d) is expected to give you different answers, up to the floating point round-off error, compared to (a+c+d+b).例如,与 (a+c+d+b) 相比,添加 (a+b+c+d) 预计会给您不同的答案,直至浮点舍入误差。 This is especially an issue in parallel computing where the orders of the accumulation from multiple parallel thread is not ensured.这在并行计算中尤其是一个问题,其中无法确保来自多个并行线程的累积顺序。

You can either force the operation order or use higher precision, like double, to reduce this error.您可以强制操作顺序或使用更高的精度(如双精度)来减少此错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM