Skip to content

Instantly share code, notes, and snippets.

@dylanjm
Created March 14, 2024 18:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dylanjm/c1750b31ae44b9c598d38e756bf5932a to your computer and use it in GitHub Desktop.
Save dylanjm/c1750b31ae44b9c598d38e756bf5932a to your computer and use it in GitHub Desktop.
A python script that plots the cobweb diagrams of the iterative tent map. This script uses the python 'decimal' library to avoid floating point arithmetic error propagation. This plot will run until the iteration values "escapes" (i.e. reaches a value > 1)
from decimal import Decimal, getcontext
import matplotlib.pyplot as plt
# Set the desired precision
getcontext().prec = 28
# Define the tent map function using Decimal for high precision
def tent_map(x, r):
half = Decimal('0.5')
return r*x if x < half else r*(1-x)
# Generate the cobweb plot with Decimal and stop if value goes above 1
def cobweb_plot(x0, r, max_iterations):
x0, r = Decimal(x0), Decimal(r)
# Prepare the figure
plt.figure(figsize=(10, 10))
# Dense grid of x values for plotting the tent map and y = x line
x_values = [Decimal(x)/Decimal('1000') for x in range(1001)] # Decimal range 0 to 1
y_values = [tent_map(x, r) for x in x_values]
# Convert Decimal lists to floats for plotting
x_values_float = [float(x) for x in x_values]
y_values_float = [float(y) for y in y_values]
# Plot the tent map and y = x line
plt.plot(x_values_float, y_values_float, 'b', label='Tent Map')
plt.plot(x_values_float, x_values_float, 'k--', label='y = x')
# Cobweb diagram
x, y = x0, Decimal('0')
for _ in range(max_iterations):
y = tent_map(x, r)
# Draw vertical line
plt.plot([float(x), float(x)], [float(x), float(y)], 'g', linewidth=2)
# Draw horizontal line
plt.plot([float(x), float(y)], [float(y), float(y)], 'g', linewidth=2)
# Update the point
x = y
# Stop if the value goes above 1
if y > 1:
break
plt.title(f'Cobweb Plot for r={r} starting at x0={x0}')
plt.xlabel('x')
plt.ylabel('Tent Map Value')
plt.legend()
plt.grid(True)
plt.show()
# Initial point, scaling coefficient, and number of iterations
x0 = '0.05'
r = '3'
max_iterations = 20
# Generate the cobweb plot with Decimal
cobweb_plot(x0, r, max_iterations)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment