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

The normalized inner product of two sequences X = (x_1. x_n) and Y = (y_1. y_n)

ID: 3849318 • Letter: T

Question

The normalized inner product of two sequences X = (x_1. x_n) and Y = (y_1. y_n) each containing n values is given by NIP(X, Y) = sigma^n_i = 1(x_i middot y_i)/|X| middot |Y| where |X| = Squareroot sigma^n_i = 1 (x_i)^2. Write a function int calc_nip(double X[], double Y[], int n, double *nip) that calculates NIP(X, Y) for arguments X and Y stored in arrays following the usual C approach, and where n indicates the number of values in X and Y that are valid. Your function should handle two distinct cases: if n is negative, or if either |X| = 0 or |Y| = 0, then the return value of the function should be the constant NIP_INVALID, and the variable indicated by the pointer nip should not be changed in any way: otherwise, the return value of the function should be the constant NIP-VALID, and the computed NIP value should be assigned to the variable indicated by the pointer nip. Note that you do not need to define the integer constants NIP_INVALID and NIP_VALID, and you do not need to know their values. Just assume that they are predefined and available for use.

Explanation / Answer

#include <iostream>
#include <cmath>
using namespace std;

// constants
bool NIP_INVALID    = 0;
bool NIP_VALID        = 1;

// functions
double mod(double [], int);
double sigma_x_y(double X[], double Y[], int n);
int calc_nip(double X[], double Y[], int n, double *nip);


int main()
{
   double nip_value{ 0 };
   double a[] = {1, 2, 3, 4, 5};
   double b[] = {1, 2, 3, 4, 5};
   cout << "nip = " << nip_value
       << ", return value is " << calc_nip(a, b, 5, &nip_value)
       << endl;
   return 0;
}


double sigma_x_y(double X[], double Y[], int n)
{
   double total {0};
   for (int i = 0; i < n; ++i)
   {
       total += X[i] * Y[i];
   }  
   return total;
};  

double mod(double X[], int n)
{
   double total{0};
   for (int i = 0; i < n; ++i)
   {
       total += X[i]*X[i];
   }  
   return sqrt(total);
};

int calc_nip(double X[], double Y[], int n, double *nip)
{
   if (n < 0) return NIP_INVALID;

   // X
   double mod_x    = mod(X, n);
   if (mod_x < 0) return NIP_INVALID;

   // Y
   double mod_y    = mod(Y, n);
   if (mod_y < 0) return NIP_INVALID;

   double x_y        = sigma_x_y(X, Y, n);
   *nip = x_y / (mod_x * mod_y);
   return NIP_VALID;
};

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote