I'm using Python to find fixed points of a given function and then draw a cobweb plot to visualize it. Thanks to this question, I have the core of the code written and can accomplish the task, but I have a number of questions about improving the functionality of the code.
import numpy as np
import matplotlib.pyplot as plt
def f(x):
return 2*x*(1-x)
class fixpt(object):
def __init__(self, x):
self.x = x
self.f = f
def search(self, N = 1000, epsilon = 1.0E-100, store = False):
x = self.x
y = self.f(x)
n = 0
if store: values = [(x,y)]
while abs(y-x) >= epsilon and n < N:
x = f(x)
n += 1
y = f(x)
if store: values.append((x,y))
if store:
return y, values
else:
if n >= N:
return "No fixed point for given initial condition"
else:
return x, n, y
def plot(self):
res, points = self.search(store = True)
xaxis = np.linspace(0,1,1000)
plt.plot(xaxis, f(xaxis), 'b')
plt.plot(xaxis, xaxis, 'r')
for x, y in points:
plt.plot([x, x], [x, y], 'g')
plt.plot([x, y], [y, y], 'g')
plt.show()
What I'm wondering is how I can:
- Avoid the need to redefine the function
f(x)
when analyzing other functions (by, perhaps asking for user input) - Avoid the need to change the range of concern (i.e. the range in
np.linspace
) in a similar manner - Improve the structure of this code in general (I'm a Python noob and get the feeling I've created a class for little to no reason
- Most importantly: use this code iteratively to scan for fixed points for all x in a given range
search
andplot
could be standalone functions, they don't share any instance attributes. – jonrsharpe Jul 6 '14 at 19:50