-1

While looking into some MATLAB code, I found this (simplified version)

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

But it doesn't make sense to me. What is the difference with the code below?

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

Even though I don't have MATLAB, the operation seems pretty straightforward, and there would not be any confusion. But, I am also sure the author meant something.

Do you have any idea?

Dev-iL
  • 23,742
  • 7
  • 57
  • 99
Heungson
  • 61
  • 5

1 Answers1

2

Let's create a simple "unit test":

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

Which outputs:

>> 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

So the first conclusion is that the codes are equivalent for common scenarios (within numerical error).

As to why it was done that way - I can only speculate that s = sign(is) ... s*abs(is) was some way to treat sign's output for complex numbers (without realizing it could be done in a simpler way).

Dev-iL
  • 23,742
  • 7
  • 57
  • 99
  • Sorry for the late response and thanks for the effort. I still don't see any advantage. Maybe it's simply that the author left it there by mistake after deleting other lines. – Heungson Jan 16 '18 at 07:51