はじめに
連立方程式をクラメルの公式で解くことにします
Pythonコード
from sympy import factorint
import matplotlib.pyplot as plt
import numpy as np
# --- 係数の設定 / Coefficients ---
a1, b1, c1 = 2, 3, 8
a2, b2, c2 = 4, -1, 2
# 係数のプリント / Print Coefficients
print(f"a1 = {a1}, b1 = {b1}, c1 = {c1}")
print(f"a2 = {a2}, b2 = {b2}, c2 = {c2}")
# --- 積の計算 / Products for D, Dx, Dy ---
ab1 = a1 * b2
ab2 = a2 * b1
cb1 = c1 * b2
cb2 = c2 * b1
ac1 = a1 * c2
ac2 = a2 * c1
# --- 出力 / Print results ---
print(f"a1 * b2 = {a1} * {b2} = {ab1} → 素因数分解 / Prime factors: {factorint(abs(ab1))}")
print(f"a2 * b1 = {a2} * {b1} = {ab2} → 素因数分解 / Prime factors: {factorint(abs(ab2))}")
print(f"→ D = a1*b2 - a2*b1 = {ab1} - {ab2} = {ab1 - ab2}")
print(f"\nc1 * b2 = {c1} * {b2} = {cb1} → 素因数分解 / Prime factors: {factorint(abs(cb1))}")
print(f"c2 * b1 = {c2} * {b1} = {cb2} → 素因数分解 / Prime factors: {factorint(abs(cb2))}")
print(f"→ Dx = c1*b2 - c2*b1 = {cb1} - {cb2} = {cb1 - cb2}")
print(f"\na1 * c2 = {a1} * {c2} = {ac1} → 素因数分解 / Prime factors: {factorint(abs(ac1))}")
print(f"a2 * c1 = {a2} * {c1} = {ac2} → 素因数分解 / Prime factors: {factorint(abs(ac2))}")
print(f"→ Dy = a1*c2 - a2*c1 = {ac1} - {ac2} = {ac1 - ac2}")
# --- 連立方程式をクラメルの公式で解く / Solve the system ---
D = ab1 - ab2
Dx = cb1 - cb2
Dy = ac1 - ac2
# 結果を表示 / Show results
if D == 0:
print("\n 解なしまたは無数の解 / No unique solution")
else:
x = Dx / D # x value
y = Dy / D # y value
print(f"\n 解 / Solution: x = {x}, y = {y}")
# --- 最小二乗法での解法 (Least Squares Method) ---
# 最小二乗法を使って連立方程式を解く
A = np.array([[a1, b1], [a2, b2]]) # Coefficient matrix
b = np.array([c1, c2]) # Constants vector
# Solve using Least Squares Method (lstsq)
x_ls, residuals, rank, s = np.linalg.lstsq(A, b, rcond=None)
y_ls = x_ls[1] # y value is the second element
x_ls = x_ls[0] # x value is the first element
# 最小二乗法による解を表示
print(f"\n 最小二乗法で解く / Solution using Least Squares: x = {x_ls}, y = {y_ls}")
# --- 連立方程式の式に対応する直線の定義 / Define lines from equations ---
def line1(x):
return (c1 - a1 * x) / b1
def line2(x):
return (c2 - a2 * x) / b2
# --- プロットの準備 / Prepare to plot ---
x_vals = list(range(-10, 11))
y1_vals = [line1(x) for x in x_vals]
y2_vals = [line2(x) for x in x_vals]
# --- グラフ描画 / Plot the graph ---
plt.figure(figsize=(6, 6))
plt.plot(x_vals, y1_vals, label=f"{a1}x + {b1}y = {c1}", color='blue')
plt.plot(x_vals, y2_vals, label=f"{a2}x + {b2}y = {c2}", color='red')
# --- 解を描画 / Plot the solution point ---
plt.plot(x, y, 'go', label=f"Solution: ({x}, {y})", markersize=8)
plt.plot(x_ls, y_ls, 'bo', label=f"Least Squares Solution: ({x_ls}, {y_ls})", markersize=8)
# --- 装飾 / Decorate ---
plt.axhline(0, color='black', linewidth=0.5)
plt.axvline(0, color='black', linewidth=0.5)
plt.grid(True)
plt.xlabel("x")
plt.ylabel("y")
plt.title("Graph of Two Linear Equations and Their Intersection")
plt.legend()
plt.tight_layout()
plt.show()
結果