【问题标题】:Why compute the sign and multiply again by the absolute value?为什么要计算符号并再次乘以绝对值?
【发布时间】:2017-11-08 06:41:09
【问题描述】:

在查看一些 MATLAB 代码时,我发现了这个(简化版)

is = 1.414 % just any floating point value
tol=1.e-4
s=sign(is); if(s==0), s=1; end;
is=s*abs(is)*tol/eps

但这对我来说没有意义。和下面的代码有什么区别?

tol=1.e-4
is=is*tol/eps

虽然我没有 MATLAB,但操作看起来很简单,不会有任何混淆。但是,我也确信作者的意思是。

你有什么想法吗?

【问题讨论】:

  • s 是否在代码中的其他任何地方使用过?
  • @ammportal - s 不在其他地方使用。
  • 那我看不出有什么理由使用复杂的代码。您编写的代码应该可以正常工作

标签: matlab sign equivalent epsilon


【解决方案1】:

让我们创建一个简单的“单元测试”:

function q47173141
TOL = 1E-4;
% Positive:
num = 3;
evalAndPrintBoth(num);
% Negative:
num = -2;
evalAndPrintBoth(num);
% Zero:
num = 0;
evalAndPrintBoth(num);
% Complex:
num = 1+1i;
evalAndPrintBoth(num);
% Imaginary 1:
num = 0.2i;
evalAndPrintBoth(num);
% Imaginary 2:
num = -2i;
evalAndPrintBoth(num);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function evalAndPrintBoth(num)
  disp('------------------------');
  disp(num2str(num));
  disp(num2str(orig(num)));
  disp(num2str(shortfun(num)));
end

function out = orig(is)
  s=sign(is); if(s==0), s=1; end
  out = s*abs(is)*TOL/eps;
end

function out = shortfun(is)
  out = is*TOL/eps;
end

end

哪些输出:

>> q47173141
------------------------
3
1351079888211.149
1351079888211.149
------------------------
-2
-900719925474.0992
-900719925474.0992
------------------------
0
0
0
------------------------
1+1i
450359962737.0496+450359962737.0496i
450359962737.0496+450359962737.0496i
------------------------
0+0.2i
0+90071992547.4099i
0+90071992547.4099i
------------------------
0-2i
0-900719925474.0992i
0-900719925474.0992i

所以第一个结论是代码对于常见场景是等价的(在数值误差范围内)。

至于为什么这样做 - 我只能推测 s = sign(is) ... s*abs(is) 是处理 sign 的复数输出的某种方式(没有意识到它可以以更简单的方式完成)。

【讨论】:

  • 很抱歉回复晚了,感谢您的努力。我仍然看不到任何优势。可能只是作者删掉其他几行后不小心把它放在那里了。
猜你喜欢
  • 2021-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-30
  • 2017-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多