Write a python function cobwebf x0 n xmin xmax ymin y max to
Write a python function cobweb(f, x0, n, xmin, xmax, ymin, y max) to draw a cobweb plot of fixed point iteration, where f is the name of function to plot; x0 is the starting point value of x; n is the number of fixed point iterations to perform; xmin and xmax are the minimum and maximum values of the x axis on the plot and ymin and ymax are the minimum and maximum values of the v axis on the plot. Demonstrate that your cobweb plot works with the function call: cobweb(cos, 1.0, 200, 0, 1.5, 0, 1) Use the following code as a starting point. import matplotlib.pyplot as plt %matplotlib inline import numpy as np def cob_plot(f, x0, n): xvals = [0]*(n+1) xvals[0] = x0 forjj in range(1, n+1): xvals[jj] = f(xvals[jj-1]) plt.scatter(xvals[0:n], xvals[l:]) # To plot the points plt.scatter(xvals[1:], xvals[1:]) # To plot the points y=x for kk in range(1, n): plt.plot([xvals[kk-1], xvals[kk]], [xvals[kk], xvals[kk]], color=\"k\", ls=\"--\") # Plot the horizontal bar plt.plot([xvals[kk], xvals[kk]], [xvals[kk], xvals[kk+1]], color=\"k, , ls=\"--\") # Plot the vertical bar plt.xlabel(\"$x_{n-1}$\") plt.ylabel(\"$x_{n}$\")
Solution
f = lambda x: np.cos(x)
def cobweb(f,x0,n,xmin,xmax,ymin,ymax):
plt.axhline(linewidth=1.0, color=\"black\")
plt.axvline(linewidth=1.0, color=\"black\")
plt.ylim((ymin,ymax))
indep = np.linspace(xmin,xmax,5000)
diag = lambda x: x
plt.plot(indep,f(indep),\'b\')
plt.plot(indep,diag(indep),\'black\')
y0 = f(x0)
for i in range(n):
plt.hlines(y0, x0, y0,\'r\')
x0 = y0
y0 = f(x0)
plt.vlines(x0, x0,y0,\'r\')
return
