使用Python來繪圖二元一次方程式
好課程介紹:小孩學Python程式的入門課:http://bit.ly/TeachYourKidsToCode大人學Python的進階課:https://bit.ly/100DaysOfCodePython
七年級的小孩遇到數學總是難以理解的二元一次方程式,以前我也是遇到這類問題。可以用網路工具https://www.geogebra.org/graphing?lang=zh-TW解,也可以寫程式解。順便問他兩個二元一次方程式無解是甚麼意思,用圖形一看就知道。是兩條永不相交的平行線。所以當有女生說我們是平行線,就是無解Orz…。
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
# Define the equation
def equation(x, y):
return 2 * x + 3 * y - 6
# Define the x and y ranges
x = np.linspace(-10, 10, 100)
y = np.linspace(-10, 10, 100)
# Calculate the equation for each (x, y) pair
result = []
for i in x:
row = []
for j in y:
row.append(equation(i, j))
result.append(row)
# Create a figure and axes object
fig, ax = plt.subplots()
# Initialize the contour plot
contour = ax.contour(x, y, result, levels=[0])
plt.clabel(contour, inline=True, fontsize=10)
# Define the animation function
def animate(i):
global contour
ax.clear()
contour = ax.contour(x, y, result, levels=[0])
plt.clabel(contour, inline=True, fontsize=10)
ax.set_title(f"Frame {i}")
# Create the animation object and save it
ani = animation.FuncAnimation(fig, animate, frames=50, interval=100, blit=False)
ani.save('animation.gif', writer='pillow')
結果: