Lab09: C++¶
1. (10 points)
Use loop to generate the 12 by 12 times table. Compile and run. You don’t have to worry much about formatting, but the output should have 12 rows with numbers separated by spaces.
In [ ]:
2. (10 points)
Write a function that takes a vector of doubles returns the squared vector. Compile and run the function with the initial vector containing 1.0, 2.0, 3.0, 4.0, 5.0.
In [ ]:
3. (10 points)
Convert the function from Exercise 2 so that it works for lists or vectors of ints, floats and doubles.
In [ ]:
4. (10 pionts)
Write a function to calculate the mean of a vector of numbers using
accumulate
from the <numeric>
library. Compile and test with
some vectors.
In [ ]:
5. (10 points)
Generate 1000 random points from the exponential distribution and save
as a comma-separated values (CSV) file. Open the file in Python and plot
the distribution using plt.hist
.
In [ ]:
6. (20 points)
Implement Newton’s method in 1D for root finding. Pass in the function
and gradient as generalized function pointers. Use the method to find
all roots of the polynomial equation \(f(x) = x^3 - 7x - 6\). You
may use the std::abs
and std::pow
from the cmath
library.
In [17]:
f = lambda x: x**3 - 7*x - 6
r = np.roots([1, 0, -7, -6])
xi = np.linspace(-2.5, 3.5, 100)
plt.plot(xi, f(xi))
plt.scatter(r, np.zeros_like(r), c='red')
plt.axhline(0)
plt.show()

7. (30 points)
Use the Eigen library to
- Generate 10 x-coordinates linearly spaced between 10 and 15
- Generate 10 random y-values as \(y = 3x^2 - 7x + 2 + \epsilon\) where \(\epsilon \sim 10 N(0,1)\)
- Find the length of \(x\) and \(y\) and the Euclidean distance between \(x\) and \(y\)
- Find the correlation between \(x\) and \(y\) using
- Solve the linear system to find a quadratic fit for this data
If you use the seed 12345 for the random number generator, you should get the following solutions.
In [21]:
x = np.array('10 10.5556 11.1111 11.6667 12.2222 12.7778 13.3333 13.8889 14.4444 15'.split()).astype('float')
y = np.array('232.862 264.056 310.697 322.345 359.037 412.095 448.471 468.163 533.646 579.763'.split()).astype('float')
In [22]:
np.linalg.norm(x), np.linalg.norm(y)
Out[22]:
(39.84924833168124, 1290.087239415614)
In [23]:
np.linalg.norm(x-y)
Out[23]:
1250.6696992541235
In [24]:
np.corrcoef(x, y)[0,1]
Out[24]:
0.9940830052398306
In [25]:
X = np.c_[np.ones_like(x), x, x**2]
np.linalg.lstsq(X, y, rcond=None)[0]
Out[25]:
array([100.9138974 , -22.66697873, 3.62437276])
Note: Remember to indicate the location of the eigen3 headers using
the -I
flag
In [ ]: