Fibonacci Sequence in Python
The Fibonacci sequence is a fundamental mathematical sequence where each number is the sum of the two preceding ones, starting from 0 and 1. So, the sequence begins 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on. It has numerous applications in various fields, including mathematics, biology, art, and computer science and appears in natural phenomena, such as the arrangement of leaves on a stem or the spirals in a seashell.
import matplotlib.pyplot as plt
import numpy as np
# Get user input for the number of Fibonacci numbers
user_input = int(input("Enter the number of Fibonacci numbers (limit 15): "))
user_input = min(user_input, 15) # Limit user input to 15
# Generate Fibonacci sequence
fibonacci = [0, 1]
while len(fibonacci) < user_input:
fibonacci.append(fibonacci[-1] + fibonacci[-2])
# Calculate coordinates for the Fibonacci spiral
x_coords = []
y_coords = []
angle = 0
for fib_num in fibonacci:
x = fib_num * np.cos(np.radians(angle))
y = fib_num * np.sin(np.radians(angle))
x_coords.append(x)
y_coords.append(y)
angle += 90
# Print calculated coordinates
print("Fibonacci Numbers:", fibonacci)
print("Calculated Coordinates:")
for i in range(len(fibonacci)):
print(f"F({i}): ({x_coords[i]:.2f}, {y_coords[i]:.2f})")
# Create the plot
plt.figure(figsize=(8, 8))
plt.plot(x_coords, y_coords, marker='o')
# Annotate each point with the corresponding Fibonacci number
for i, fib_num in enumerate(fibonacci):
plt.annotate(fib_num, (x_coords[i], y_coords[i]))
# Add labels and title
plt.xlabel("X Coordinate")
plt.ylabel("Y Coordinate")
plt.title("Fibonacci Spiral")
plt.grid()
plt.show()