0

I'm doing some testing of time domain convolution vs frequency domain multiplication, in particular that you can achieve the same result as multiplying two base 10 numbers by treating them as vectors, doing a DFT, multiplying, then recombining them as follows:

format long
multiply = 527283*426715
a = [5 2 7 2 8 3];
b = [4 2 6 7 1 5];
len = length(a)+length(b) - 1; % the length of the convolution result
temp = ifft(fft(a,len).*fft(b,len));
% add the numbers for each index up
result = 0;
for i = 1:length(temp)
    result = result + temp(i)*10^(length(temp)-i);
end
result
result == multiply

When I run that code, I get 0 at the end, implying that the two numbers aren't equal. If I reduce the order of magnitude of the input by two then it returns 1 like it should. Where does this numerical error come from/can it be avoided?

chris
  • 4,840
  • 5
  • 35
  • 66
  • Floating point arithmetic has a precision and does not retunr perfect results: http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html – Daniel Aug 02 '14 at 08:06
  • So basically number's greater than whatever precision the float is kept will have some but errors – chris Aug 02 '14 at 08:52

1 Answers1

1

If a and b are floating-point numbers you should never ever use a == b to check for equality. You should instead compare them up to a tolerance abs(a-b) < tol where tol could be, for example, 10e-6.

It can be confusing since you are declaring multiply as the product of two integers, nevertheless in Matlab everything is a double, unless explicitly specified.

gire
  • 1,105
  • 1
  • 6
  • 16