CSCI 2202 Python Programming for Scientists Lab 10
Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: daixieit
CsC1 2202 PYTnoN PRocRAMMINc FoR scIENTIsTs LAB 10
(1) Newton’s method is fast, but prone to problems like division by zero. We examine how Newton’s method fails: For this, solve f (x) = tanh(x) = 0 (hyperbolic Tan) (i) Start with an initial guess x0 = 1.08. Plot the tangent (and the function at each iteration of Newton’s method. (ii) Repeat with an initial guess x0 = 1.09.
Note: = 1 一 tanh(x)2 .
Write a function to plot the curve and the tangent (like the one shown below), that you can call from your program, After each call to plot line, you will need a command input("Hit Enter to Continue") for the program to move to the next iteration.
def plot line(f, xn, fxn, slope):
# Plot both f(x) and the tangent
xf = np.linspace(-2,2,100)
yf = f(xf)
xt = np.linspace(xn-2, xn+2,10)
yt = slope*xt + (fxn - slope*xn) # Straight line: ax + b plt.figure()
plt.plot(xt, yt, ’r-’, xf, yf, ’b-’)
plt.grid(’on’)
plt.xlabel(’x’)
plt.ylabel(’f(x)’)
plt.pause(1) # 1 second delay
plt.clf() # clear the current figure
(2) (a) Write a function readDatFile(inFile) to read in the coffee cooling data. The function should take a filename as a parameter (input by the user) and should return the numpy arrays x, y containing the data.
(b) The file coffeeCooling.txt alongside, holds the time, Temp data for coffee cooling. Using the program written above, read the data from the file and re- turn numpy arrays for the time and Temp data. Then using matplotlib.pyplot to scatter-plot the data. Use the matplotlib.pyplot functions xlabel( ), ylabel( ) to label the axes appropriately.
2022-02-14