Matlab的数组运算误差

Matlab的数组运算误差

本文介绍了Matlab的数组运算误差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我试图模仿我的正弦逼近MATLAB中我发现了一个奇怪的问题。问题是,当我申请我的功能阵列,它返回1的结果,而应用功能,个人价值提供了一个稍微不同的结果。

When i am trying to simulate my sine approximation in matlab i found a strange problem. The problem is that when i apply my function to an array, it returns one results, whereas applying functions to individual values ​​gives a slightly different result.

我能得到在这个例子中相同的行为:

I was able to get same behaviour in this example:

z = single(0:0.001:1);
F = @(x) (x.^2 - single(1.2342320e-001)).*x.^2;  %some test function

z(999)        % Returns 9.9800003e-001
F(z(999))     % Returns 8.6909407e-001
temp = F(z);
temp(999)     % Voila! It returns 8.6909401e-001

此外,我发现了一些东西。其中之一是,第一个结果是正确的(不是后者)。其次,是项重排有时解决问题。所以,我不知道如何摆脱这一点。

Also I found a few things. One is that first result is right (not the latter). Second, is that rearrangement of terms sometimes solves the problem. So i have no idea how to get rid of that.

推荐答案

使用单precision号码,无论结果是平等(差大于单一的相对精度较小类型)。下面的语句计算结果为true:

Using single-precision numbers, both results are "equal" (difference is smaller than the relative accuracy of the single type). The following statement evaluates to true:

max(abs( arrayfun(F,z) - F(z) )) < eps('single')


修改

如果你真的想在这个控制,可以尝试禁用MATLAB加速器,迫使它使用相同的执行路径为经常和矢量code:


EDIT

If you really want to have control over this, you can try disabling the MATLAB accelerator to force it to use the same execution paths for both regular and vectorized code:

feature('jit', 'off')
feature('accel', 'off')
max(abs( arrayfun(F,z) - F(z) ))

feature('jit', 'on')
feature('accel', 'on')
max(abs( arrayfun(F,z) - F(z) ))

有关结果第一/第二分别是:

The result for the first/second respectively:

ans =
     0
ans =
   5.9605e-08

显然,在默认情况下都加速器与刚刚在时间编译器被接通。

Obviously, by default both the accelerator and the just-in-time compiler are turned on.

这篇关于Matlab的数组运算误差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 10:19