2.6. Solutions to Exercises#
Exercise 2.1
var=3.5
# Example: one space is actually enough! But is discouraged, as you can see
# by the fact the the notebook made it red colored.
def myfunction():
var2 = int(var)
print(var2)
# Once you've started a code block though with a specific indentaton, then you cant change
# it anymore.
def myfunction():
var2 = int(var)
print(var2)
Exercise 2.2
def myfunction(var):
var2 = int(var)
print(var2)
Exercise 2.3
def print_status4(x, y, z):
print("The value of the first input variable is ", x)
print("The value of the second input variable is ", y)
print("The value of the third input variable is ", z)
print_status4(1,2,3)
Exercise 2.4 (a)
# Your function here
def product_and_sum(a,b):
return a*b, a+b
(b)
a=1.5
b=2.5
p,s = product_and_sum(a,b)
print("Sum is:", s)
print("Product is:", p)
Exercise 2.5 (a)
help(abs)
help(int)
help(input)
(b)
from glob import glob
help(glob)
glob("../*")
# It returns list of files and folders in the parent directory of that
# in which this notebook is stored
Exercise 2.6 (a)
def f(x): # All differentiable functions are correct
return np.sin(x)
print(f(0), f(1))
Exercise 2.6 (b)
def determine_slope(a, epsilon):
dy = f(a + epsilon) - f(a - epsilon)
dx = 2 * epsilon
return dy/dx
Exercise 2.6 (c)
def print_tangent(a, epsilon):
m = determine_slope(a, epsilon)
b = f(a) - m*a
print("The tangent line of the function is: y = {}x + {}".format(round(m,3), round(b,3)))
epsilon = 0.01 # Depending on the function, a larger epsilon may also be sufficient or a smaller one may be required.
a = 0 # Again, an arbitrary choice.
print_tangent(a, epsilon)
Exercise 2.7
x = np.array([1.1, 3.4, 4.7, 5.3, 6.8])
y = np.array([1.05, 1.62, 1.95, 2.10, 2.47])
x_test = np.linspace(0,1.2*max(x),1000)
def func(x,a,b):
return a*x+b
y_test = func(x_test,.27,0.7)
plt.figure()
plt.plot(x,y,'k.', label='measurements')
plt.plot(x_test,y_test,'r--', label='fitline')
plt.xlabel('$x$')
plt.ylabel('$y$')
plt.xlim(0,1.1*max(x))
plt.show()
Exercise 2.8 (a)
k = 8.988e9
def F(q1,q2,r):
return k*q1*q2/r**2
Exercise 2.8 (b)
r = np.arange(0.5E-10,6E-10,0.1E-10)
F_q = F(1.602E-19,-1.602E-19,r)
plt.figure()
plt.plot(r,F_q,'k.')
plt.xlabel('$r$ (m)')
plt.ylabel('$F$ (N)')
plt.show()