import matplotlib.pyplot as plt

# 以下の連立方程式を解く
# 3x - 2y + z = 3
# 2x + 3y - z = 1
# x + 3y - 2z = 2

# とりあえず適当な値で初期化
x = 0
y = 0
z = 0

eps = 1.0e-6
step = []
xResult = []
yResult = []
zResult = []

for i in range(100):
    xp = x
    yp = y
    zp = z

    x = 2/3*yp - 1/3*zp + 1
    y = -2/3*xp + 1/3*zp + 1/3
    z = 1/2*xp + 3/2*yp - 1
    
    step.append(i)
    xResult.append(x)
    yResult.append(y)
    zResult.append(z)

    # 前回とほぼ同じ値だったら、それが解なのでループ脱出
    if abs(x - xp) + abs(y - yp) + abs(z - zp) <= eps:
        break

plt.plot(step, xResult, label="x")
plt.plot(step, yResult, label="y")
plt.plot(step, zResult, label="z")
plt.xlabel('x - step')
plt.ylabel('y - solution')
plt.title('Jacobi method')
plt.grid(axis='both')
plt.legend() # これがないとラベル出ない
plt.show()

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: