Puzzle DB14


Compute the sum of the squared difference between the elements of two arrays of doubles

[E-6]Write a function that operates on two arrays of double precision floats, a and b. Both arrays are the same size. For each index j, compute (a[j]-b[j])2 and add that to a sum. Output of a test run:

x:
  2.0000   0.0000  -3.0000   0.0000   0.0000
  0.0000   0.0000   0.0000   0.0000   0.0000
y:
  2.0000  -2.0000  -3.0000   2.0000   2.0000
  2.0000  -2.0000   2.0000   2.0000   2.0000

sum = 32.000000

For further testing, initialize the arrays with random values using puzzle D07 or D10. Here is a testing framework:

double squareDiffArray( int size, double a[], double b[] )
{
...
}

void printArrayDouble( int size, double arr[] )
{
  const int N = 5;
  int j;

  for ( j=0; j<size; j++ )
  {
    if ( j%N == N-1 )
      printf("%8.4lf\n", arr[j] );
    else
      printf("%8.4lf ", arr[j] );
  }
}

#define SIZE 10
int main()
{
  double x[ SIZE ] = { 2, 0,-3, 0, 0, 0, 0, 0, 0, 0 };
  double y[ SIZE ] = { 2.0, -2.0, -3.0, 2.0, 2.0, 2.0, -2.0, 2.0, 2.0, 2.0  };

  printf("x:\n");
  printArrayDouble( SIZE, x );
  printf("y:\n");
  printArrayDouble( SIZE, y );
  printf("\n");
  printf("sum = %lf\n", squareDiffArray( SIZE, x, y ) );
  
  return 0;
}


Answer         Next Page         Previous Page Home