Answer the following questions by slicing a numpy array containing the given array. Each answer should be done using slicing and summing multiple copies of the array. Do not use for
loops or any other approach. See example answer. 4 Points each.
In [1]:
import numpy as np
x = np.array([1, 4, 7, 11, 34, -3, 5, 7, 5, 2, 3, 13])
###-------###
x[::2]
Out[1]:
In [2]:
x[:-1] + x[1:]
Out[2]:
In [3]:
x[1:] - x[:-1]
Out[3]:
In [4]:
x[::2] / x[1::2]
Out[4]:
In [5]:
N = len(x)
x[:N // 2] * x[N // 2:]
Out[5]:
Use the two matrices given to answer the following problems. Answer in Python.
$$ \mathbf{A} = \left[\begin{array}{lcr} 3 & 2 & -1\\ 6 & 4 & -2\\ 5 & 0 & 3\\ \end{array}\right] \quad \mathbf{B} = \left[\begin{array}{lcr} 2 & 3 & 2\\ 3 & -4 & -2\\ 4 & -1 & 1\\ \end{array}\right] $$
In [6]:
import numpy.linalg as linalg
A = np.array([ [3, 2, -1], [6, 4, -2], [5, 0, 3]])
B = np.array([ [2, 3, 2], [3, -4, -2], [4, -1, 1]])
linalg.matrix_rank(A)
Out[6]:
In [7]:
A @ B
Out[7]:
In [8]:
eig_vals, eig_vecs = linalg.eig(B)
eig_vecs[:,1]
Out[8]:
In [9]:
b = np.array([14, -1, 11])
linalg.solve(B, b)
Out[9]:
Evaluate the following definite integrals using the quad
function and the lambda
keyword. You may only report your answer in Python and you should only print the integral area to 4 significant figures and nothing else. Do not define a function, use lambda
to define your integrands if necessary. 4 points each.
$ \int_0^{\pi / 4} \tan x\, dx $
$\int_{-2}^0 3x^3\, dx$
$\int_0^3 4x^2 - x \,dx$
$\int_{-2}^2 \sin x^2 \, dx$
In [10]:
from scipy.integrate import quad
ans, err = quad(lambda x: np.tan(x), 0, np.pi / 4)
print(f'{ans:.4}')
In [11]:
ans, err = quad(lambda x: 3*x**3, -2, 0)
print(f'{ans:.4}')
In [12]:
ans, err = quad(lambda x: 4 * x**2 - x, 0, 3)
print(f'{ans:.4}')
In [13]:
ans, err = quad(lambda x: np.sin(x**2), -2, 2)
print(f'{ans:.4}')
Plot [4 points] & evaluate [4 points] the following definite integral. Report your answer to 4 significant figures.
$$ \int_0^3 f(x)\, dx, \quad f(x) = \; \left. \begin{array}{llr} x^2 & \textrm{if} & |x| < 2\\ 4 & \textrm{if} & x > 2 \\ x & \textrm{otherwise} & \\ \end{array}\right\} $$Evlaute the following integral. Report your answer to 4 significant figures.
$$ \int_0^{1}\int_{-2 x}^x \sin xy \,dy\, dx $$
In [14]:
def fxn(x):
if abs(x) < 2:
return x ** 2
elif x > 2:
return 4
else:
x
npfxn = np.vectorize(fxn)
#remove 1 point if they put lambda x: npfxn(x) instead of just the name.
ans, err = quad(npfxn, 0, 3)
print(f'{ans:.4}')
In [15]:
def integrand(x):
ans, err = quad(lambda y: np.sin(x * y), -2* x, x)
return ans
ans, err = quad(integrand, 0, 1)
print(f'{ans:.4}')
Use the given datasets to compute the requested quantities:
x = [-0.42,1.34,1.6,2.65,3.53,4.48,5.48,6.21,7.49,8.14,8.91,10.1]
y = [1.58,1.61,2.04,5.47,9.8,16.46,25.34,33.32,49.7,58.79,71.26,93.34]
In [16]:
x = [-0.42,1.34,1.6,2.65,3.53,4.48,5.48,6.21,7.49,8.14,8.91,10.1]
y = [1.58,1.61,2.04,5.47,9.8,16.46,25.34,33.32,49.7,58.79,71.26,93.34]
x = np.array(x)
y = np.array(y)
import matplotlib.pyplot as plt
%matplotlib inline
plt.plot(x,y, 'o-')
plt.xlabel('x')
plt.ylabel('y')
plt.show()
In [17]:
forward = (y[1:] - y[:-1]) / (x[1:] - x[:-1])
diff = 0.5 * (forward[1:] + forward[:-1])
print(np.round(diff, decimals=2))
In [18]:
integral = np.sum( y[:-1] * (x[1:] - x[:-1]))
print(f'{integral:.2f}')
In [19]:
integral = np.sum( (y[:1] + y[:-1]) * (x[1:] - x[:-1])) / 2
print(f'{integral:.2f}')
Write a function which will compute a confidence interval given a sample and confidence level. Your function should optionally take in the population standard deviation. Your function should return a value, $y$, such that $\mu = \bar{x} \pm y$. Demonstrate it on 3 examples: (1) 10 samples with known population standard deviation, (2) 30 samples with unknonw population standard deviation, and (3) 5 samples with unknown population standard deviation. You must both define the function (+ document it) and show it on these 3 examples to receive full credit. The confidence level (90%, 95%, etc) should be adjustable.
In [20]:
import scipy.stats as ss
def conf_interval(samples, confidence_level=0.95, sigma=None):
'''
computes confidence interval given samples
Parameters
---------
samples : list
The samples
confidence_level : float, optional
The confidence level. Default is 95%
sigam : float, optional
Population standard deviation. Default is None (unpsecified)
Returns
---------
float
A value, y, such that the population mean lies at the sample mean +/- y
'''
sample_mean = np.mean(samples)
sample_var = np.var(samples, ddof=1)
if sigma is not None:
sample_var = sigma * sigma
if sigma is None and len(samples) < 25:
score = ss.t.ppf((1 - confidence_level) / 2, df=len(samples)-1)
else:
score = ss.norm.ppf((1 - confidence_level) / 2)
y = -score * np.sqrt(sample_var / len(samples))
return y
In [21]:
# case 1
samples = np.random.normal(size=10)
y = conf_interval(samples, 0.90, 1)
print(f'{np.mean(samples):.2} +/- {y:.2}'.format())
In [22]:
# case 2
samples = np.random.normal(size=30)
y = conf_interval(samples, 0.95)
print(f'{np.mean(samples):.2} +/- {y:.2}'.format())
In [23]:
# case 1
samples = np.random.normal(size=5)
y = conf_interval(samples, 0.99)
print(f'{np.mean(samples):.2} +/- {y:.2}'.format())