C and C++ΒΆ

Exercise 1 (25 points)

  • Write a function in C that calculates the mean of an array of doubles, putting the function declaration and function definition in separate files (10 points)
  • Write a driver program to call the function with the inputs being an array containing the numbers 1,2,3,4,5 and print the results to standard output (5 pints)
  • Write a makefile that compiles the executable upon calling make at the command line and removes all generated files upon calling make clean (10 points)
In [1]:




Exercise 2 (25 points)

  • Write a function matrix_multiply in C with the following function signature

    void matrix_multiply(double** A, double **B, double **C, int m, int n, int p)
    

    The function multiples an \(m \times n\) matrix \(A\) with an \(n \times p\) matrix \(B\) and gives the result in the matrix \(C\) (10 points)

  • Write a function to pretty print a matrix to standard output, and use it to display \(A\) and \(B\). The output should look something like this (5 point):

    [[3.0, 0.1, 5.0, 18.1],
       [7.8, 7.9, 3.2, 1.0],
       [6.1, 5.5, 8.9, 4.1]]
    
  • Write a driver program to test it with the following matrices. Matrices should be generated using dynamic memory allocation, freeing up the memory when done (10 points)

A = \pmatrix{1 & 2 & 3\\4 & 5 & 6}, B = \pmatrix{1 & 2 & 3 & 4\\5 & 6 & 7 & 8\\9 & 0 & 1 & 2}
In [1]:




Exercise 3 (25 points)

  • Implement the secant method in 1D for root finding in C++. Pass in the function as a generalized function pointer. Use the method to find all roots of the polynomial equation \(f(x) = x^3 - 7x - 6\) (20 points)
  • Write the roots to a text file that can be read in Python and plot the roots and polynomial using Python (5 points)
In [1]:




Exercise 4 (25 points)

You are given the following set of data

x = \pmatrix{0 \\ 1 \\ 2 \\ 3 \\ 4 \\ 5 \\ 6 \\ 7 \\ 8 \\ 9}, y = \pmatrix{1.5 \\ 7.5 \\ 10.7 \\ 7.9 \\ -2.0 \\ -12.4 \\ -28.6 \\ -46.3 \\ -68.1 \\ -97.1}
  • Write your own gradient descent optimization function in C++ to find the least squares solution for the coefficients \(\beta\) of a quadratic polynomial. You may use the armadillo library (20 points)
  • Write the solution to a text file that can be read in Python and plot the least squares quadratic fit together with the data points using Python (5 points)
In [1]: