Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

1 +21 z1). The variables are in floating- (6 marks) s. ( The magnitude of a vect

ID: 3607633 • Letter: 1

Question

1 +21 z1). The variables are in floating- (6 marks) s. ( The magnitude of a vector (id, ys,zl)is vaxi yltyl z121). The variables are in to point. Wirite a function definition that returns the magnitude of a given vector. (6 mantin Ans: (ii)The dot product of two vectors (x1, y1,21) and (x2, y2, 2) is x1.x2 + yly2 + z1.2. Write a function definition that takes two vectors as inputs and returns the dot product. You do not (6 marks) need to read in the values of the variables. (iii) The dot product of two vectors A and B is also lAl® IBI"cos(T), where IAI means the magnitude of vector A, and T is the angle between the two vectors. Write another function that makes use of the above two functions to find the cosine of the angleT (8 marks) Ans:

Explanation / Answer

// C code

// (1)
float magnitude(vector<float> v)
{
float m = 0;
for (int i = 0; i < v.size(); ++i)
{
m = m + v[i]*v[i];
}

return sqrt(m);
}

// (11)
float dotProduct(vector<float> v1, vector<float> v2)
{
if(v1.size() != v2.size())
{
printf("Cannot find dot dotProduct Unequal Length vectors EXIT ");
return 0;
}

float product = 0;
for (int i = 0; i < v1.size(); ++i)
{
product = product + v1[i]*v2[i];
}

return product;
}


// (111)
float cosine(vector<float> v1, vector<float> v2)
{
float magA = magnitude(v1);
float magB = magnitude(v2);

float angle = acos(dotProduct(v1,v2));


float cosine = cos((magA*magB)*angle);

return cosine;
}