Tuesday, July 14, 2009

How do i write a program that gives me the inner product of two vectors in the C programming language?

Write a program that will input two vectors of information. Each vector will contain exactly 8 floating point values. Your program will enter these values in from the standard input. Once the values have been read in, your program should call a function that will compute the inner product of these two vectors. The function should return the value back to the main program. The main program will then print out the value. You should not print the value out inside the inner product function.





The inner product of two vectors is a single number obtained by multiplying corresponding elements and then adding up their sums. For example, if vector u = (5, 1, 6, 2) and vector v = (1, 2, 3, 4) then the inner product is 33 because





(5 * 1) = 5


(1 * 2) = 2


(6 * 3) = 18


(2 * 4) = 8





and 5 + 2 + 18 + 8 is 33.





Your C program will call a function called inner that has the following interface:





float inner ( float u[] , float v[], int size ) ;

How do i write a program that gives me the inner product of two vectors in the C programming language?
float inner(float u[], float v[], int size)


{


float r;


int i;


if (size %26lt; 0) {


fprintf(stderr, "inner: size illegal\n");


exit(1);


}


if (size == 0)


return 0.0;


for (r = 0.0, i = 0; i %26lt; size; ++i)


r += u[i] * v[i];


return r;


}





#define SIZE 8





int main(void)


{


float u[SIZE], v[SIZE];


int i;


for (i = 0; i %26lt; SIZE; ++i)


scanf("%g %g\n",u + i, v + i);


printf("inner product = %g\n", inner(u, v, SIZE);


return 0;


}
Reply:In function inner, create a third vector. The third vector will receive the calculations from the first two vectors.





Here's some psuedocode:





//create float arrays to hold the numbers for each vector





//create a float array to hold the products





a)iterate through array 1 and 2 with a for loop.





b)assign the result of multiplying array1 and array2 to array3





c)Create a local variable to hold the value of the sum of the products





d) loop through array3, summing the total as you go.





e)return the local variable


Email me if you have more questions.


No comments:

Post a Comment