Cobwebbing

462 days ago by tazzalenghe

# This SAGE code is based on a sample kindly supplied by Dr Shaun Ault. 
       
def cobweb(g,z,x_0,n,huge): """ INPUT: -"g"-function -"z"-variable defining g (usually 'x' in the examples) -"x_0"-initial value of z -"n" - number of iterations to perform -"huge" - any value of x with absolute value bigger than this is so large that we cut short the loop OUTPUT: - "P" - plot showing the iterations graphically RETURN: - nothing """ # set up variable to hold x values and initialize xmin and xmax x = RDF(x_0) xmin = x-RDF(0.001) xmax = x+RDF(0.001) # dummy line to get plot structure P set up P = plot(z, z, xmin, xmax, color='gray') # loop to create cobweb for i in range(n): # new value and vertical and horizontals it gives y = g(x); P +=line( [ ( x, x ), ( x, y ) ], color='red') P +=line( [ ( x, y ), ( y, y ) ], color='orange') x = y # update xmin and xmax and break if either is too big if (y > xmax): xmax = y if (y < xmin): xmin = y if (xmin < -huge): break if (xmax > huge): break # add plot of function g and line y=x with suitable range # now that we know xmin and xmax P +=g.plot(z, xmin, xmax, color ='blue') P +=plot(z, z, xmin, xmax, color='gray') # show and tell time P.show(ymin = xmin, ymax = xmax) return 
       
cobweb(x^2-2,x,1.99999,10, 100) 
       
cobweb(x^2-2,x,0.5, 15, 10^3) 
       
cobweb(x^3-x,x,0.5, 10, 10^3) 
       
cobweb(x^3-x,x,0.5, 100, 10^3) 
       
cobweb(x^3-2*x,x,0.5, 10, 10^3) 
       
cobweb(x^3-2*x, x, 2, 100, 10^3) 
       
x = 1. dx= 1. eps = 0.000000000001 n = 0; while (abs(dx)> eps): fx = x^2-2 dfx= 2*x dx = -fx/dfx n = n+1 x = x+dx print n,x 
       
1 1.50000000000000
2 1.41666666666667
3 1.41421568627451
4 1.41421356237469
5 1.41421356237310
6 1.41421356237309
1 1.50000000000000
2 1.41666666666667
3 1.41421568627451
4 1.41421356237469
5 1.41421356237310
6 1.41421356237309