# include # include int main ( ) { double a12; double a13; double a23; double c12; double c13; double c23; int i; double pi = 3.14159265; double v1[3] = { 1.0, 0.0, -1.0 }; double v2[3] = { 4.0, 5.0, 4.0 }; double v3[3] = { 4.0, 3.0, 0.0 }; double v1_norm; double v2_norm; double v3_norm; double v1v2; double v1v3; double v2v3; // // The length of a vector is the square root of the sum of the squares // of the entries. Here are three ways to compute it. // v1_norm = sqrt ( v1[0] * v1[0] + v1[1] * v1[1] + v1[2] * v1[2] ); printf ( " ||v1|| = %g\n", v1_norm ); v2_norm = sqrt ( pow ( v2[0], 2 ) + pow ( v2[1], 2 ) + pow ( v2[2], 2 ) ); printf ( " ||v2|| = %g\n", v2_norm ); v3_norm = 0.0; for ( i = 0; i < 3; i++ ) { v3_norm = v3_norm + v3[i] * v3[i]; } v3_norm = sqrt ( v3_norm ); printf ( " ||v3|| = %g\n", v3_norm ); // // The dot product of two vectors is 0 if they are perpendicular to each other. // Here are two ways to do this. // printf ( "\n" ); v1v2 = v1[0] * v2[0] + v1[1] * v2[1] + v1[2] * v2[2]; printf ( " v1.v2 = %g\n", v1v2 ); v1v3 = v1[0] * v3[0] + v1[1] * v3[1] + v1[2] * v3[2]; printf ( " v1.v3 = %g\n", v1v3 ); v2v3 = 0.0; for ( i = 0; i < 3; i++ ) { v2v3 = v2v3 + v2[i] * v3[i]; } printf ( " v2.v3 = %g\n", v2v3 ); // // The cosine of the angle between two vectors is the dot product divided by their norms. // printf ( "\n" ); c12 = v1v2 / v1_norm / v2_norm; printf ( " cosine(v1,v2) = %g\n", c12 ); c13 = v1v3 / v1_norm / v3_norm; printf ( " cosine(v1,v3) = %g\n", c13 ); c23 = v2v3 / v2_norm / v3_norm; printf ( " cosine(v2,v3) = %g\n", c23 ); // // The ANGLE between two vectors is the inverse cosine or "arc-cosine" of the cosine. // This will come out in RADIANS unless we divide the result by PI and multiply by 180. // printf ( "\n" ); a12 = acos ( c12 ) / pi * 180; printf ( " angle(v1,v2) = %g degrees\n", a12 ); a13 = acos ( c13 ) / pi * 180; printf ( " angle(v1,v3) = %g degrees\n", a13 ); a23 = acos ( c23 ) / pi * 180; printf ( " angle(v2,v3) = %g degrees\n", a23 ); return 0; }