Search All of the Math Forum:

Views expressed in these public forums are not endorsed by NCTM or The Math Forum.

Notice: We are no longer accepting new posts, but the forums will continue to be readable.

Topic: Precision question
Replies: 1   Last Post: Oct 21, 2011 3:45 PM

 Messages: [ Previous | Next ]
 mailcwc@gmail.com Posts: 52 Registered: 7/14/05
Precision question
Posted: Oct 20, 2011 11:28 PM

I have three algorithms to calculate the inner product of vector
A(i,j) and vector V for M x N times.
With the line A = round(A), B1 = B2 = B3.
Without the line A = round(A);, B1 != B2, B2 = B3.
Is this a precision error?
Which one is correct?

clc;100
clear all;
M = 1000;
N = 1000;
P = 10;

A = 10*rand(M,N,P);
A = round(A);

% A = zeros(M,N,P);
% for i = 1:P
% A(:,:,i) = i;
% end

V = 1:P;

% Algorithm 1
A = shiftdim(A,2);
tic;
B1 = zeros(M,N);
for i = 1:M
for j = 1:N
B1(i,j) = V*A(:,i,j);
end
end
t1 = toc;
A = shiftdim(A,1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Algorithm 2
tic;
temp = zeros(M,N,P);
for i = 1:P
temp(:,:,i) = A(:,:,i)*V(i);
end

B2 = sum(temp,3);
clear temp;
t2 = toc;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Algorithm 3
tic
v = repmat(reshape(V, [1 1 P]), [M N]);
temp = bsxfun(@times, A, v);
B3 = sum(temp,3);
clear temp;
t3 = toc;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

isequal(B1,B2,B3)
isequal(B1,B2)
isequal(B2,B3)
isequal(B1,B3)
t1
t2
t3

Date Subject Author
10/20/11 mailcwc@gmail.com
10/21/11 Roger Stafford