数学Ⅰ・A 基礎問題精講 


https://colab.research.google.com/


https://www.kikagaku.co.jp/kikagaku-blog/google-colab-howto/

三次元プロット
```python
# Program Name: exponent_rule_3d_plot.py  
# Creation Date: 20250603  
# Overview: Visualize the exponent rule (ab)^n = a^n * b^n in 3D  
# Usage: Run in Python environment with matplotlib and numpy installed  

# -------------------- ライブラリのインポート / Import necessary libraries --------------------
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D  # 3Dプロットのためのモジュール

# -------------------- パラメータ設定 / Parameter settings --------------------
a_vals = np.linspace(1, 5, 50)  # aの値の範囲を1〜5で等間隔に生成 / Generate values for a from 1 to 5
b_vals = np.linspace(1, 5, 50)  # bの値の範囲を1〜5で等間隔に生成 / Generate values for b from 1 to 5
a_grid, b_grid = np.meshgrid(a_vals, b_vals)  # 格子状の座標データを作成 / Create meshgrid for 3D surface

# -------------------- 指数法則の計算 / Compute both sides of the exponent rule --------------------
n = 2  # 指数（2乗） / Exponent
lhs = (a_grid * b_grid) ** n  # 左辺 (ab)^n / Left-hand side
rhs = (a_grid ** n) * (b_grid ** n)  # 右辺 a^n * b^n / Right-hand side

# -------------------- プロット / Plotting --------------------
fig = plt.figure(figsize=(14, 6))  # グラフ全体のサイズを指定 / Set figure size

# --- (ab)^n のグラフ描画 / Plot (ab)^n ---
ax1 = fig.add_subplot(121, projection='3d')  # 1枚目の3Dプロット
ax1.plot_surface(a_grid, b_grid, lhs, cmap='viridis')  # 曲面描画
ax1.set_title('Surface of (ab)^n')  # グラフタイトル
ax1.set_xlabel('a')  # x軸ラベル
ax1.set_ylabel('b')  # y軸ラベル
ax1.set_zlabel('(ab)^n')  # z軸ラベル

# --- a^n * b^n のグラフ描画 / Plot a^n * b^n ---
ax2 = fig.add_subplot(122, projection='3d')  # 2枚目の3Dプロット
ax2.plot_surface(a_grid, b_grid, rhs, cmap='plasma')  # 曲面描画
ax2.set_title('Surface of a^n * b^n')  # グラフタイトル
ax2.set_xlabel('a')  # x軸ラベル
ax2.set_ylabel('b')  # y軸ラベル
ax2.set_zlabel('a^n * b^n')  # z軸ラベル

# --- レイアウト調整 / Layout adjustment ---
plt.tight_layout()  # 図の間隔を自動調整
plt.show()  # グラフ表示

```
因数分解
```python
# Program Name: factor_polynomial.py  
# Creation Date: 20250603  
# Overview: Factor the polynomial 2x^3 - x^2 - 18x + 9 using SymPy  
# Usage: Run in Python environment with sympy installed  

# -------------------- Install Required Libraries --------------------
!pip install sympy

# -------------------- Import Library --------------------
import sympy as sp

# -------------------- Define Symbol --------------------
x = sp.Symbol('x')

# -------------------- Define Polynomial --------------------
expr = 2*x**3 - x**2 - 18*x + 9  # 係数を元に多項式を定義 / Define the cubic polynomial

# -------------------- Factor Polynomial --------------------
factored_expr = sp.factor(expr)  # 因数分解 / Factor the polynomial

# -------------------- Output --------------------
print("Factored Expression:")
print(factored_expr)  # 結果表示 / Display the factored form


```
有理化

```python
# Program Name: rationalize_denominator.py  
# Creation Date: 20250603  
# Overview: Rationalize the denominators of two given expressions  
# Usage: Run in Python environment with sympy installed  

# -------------------- Install Required Libraries --------------------

# -------------------- Import Library --------------------
import sympy as sp

# -------------------- Define Symbols --------------------
sqrt2 = sp.sqrt(2)
sqrt3 = sp.sqrt(3)
sqrt5 = sp.sqrt(5)

# -------------------- Problem (1): 1 / (sqrt(5) + 2) --------------------
expr1 = 1 / (sqrt5 + 2)
rationalized1 = sp.simplify(expr1)


# -------------------- Output Results --------------------
print("Problem (1) Rationalized:")
sp.pprint(rationalized1, use_unicode=True)


```

連立方程式
```python
# Program Name: solve_linear_system_lu_cramer.py  
# Creation Date: 20250603  
# Overview: Solve a system of linear equations using LU decomposition and Cramer's rule  
# Usage: Run in Python environment with numpy and scipy installed  

# -------------------- Install Required Libraries --------------------
!pip install numpy scipy

# -------------------- Import Libraries --------------------
import numpy as np
from scipy.linalg import lu, solve

# -------------------- Define Coefficient Matrix and RHS Vector --------------------
# System of equations:
# ① 2x - y = 3
# ② 3x - y = -1
A = np.array([[2, -1], [3, -1]])  # Coefficient matrix / 係数行列
b = np.array([3, -1])            # RHS vector / 定数ベクトル

# -------------------- LU Decomposition --------------------
P, L, U = lu(A)
y_intermediate = solve(L, P @ b)
x_solution_lu = solve(U, y_intermediate)

# -------------------- Cramer's Rule --------------------
det_A = np.linalg.det(A)  # 行列式 / Determinant of A

# x 用の行列：Aの第1列をbで置換
A_x = A.copy()
A_x[:, 0] = b
det_A_x = np.linalg.det(A_x)

# y 用の行列：Aの第2列をbで置換
A_y = A.copy()
A_y[:, 1] = b
det_A_y = np.linalg.det(A_y)

# Cramer の公式による解
x_solution_cramer = np.array([det_A_x / det_A, det_A_y / det_A])

# -------------------- Output --------------------
print("LU Decomposition Solution [x, y]:", x_solution_lu)
print("Cramer's Rule Solution     [x, y]:", x_solution_cramer)


```
放物線
```python
# Program Name: quadratic_vertex_vs_gradient.py  
# Creation Date: 20250603  
# Overview: Compare vertex form and gradient descent result for quadratic function  
# Usage: Run in Python environment with matplotlib and numpy installed  

# -------------------- Install Required Libraries --------------------
!pip install numpy matplotlib

# -------------------- Import Libraries --------------------
import numpy as np
import matplotlib.pyplot as plt

# -------------------- Define Quadratic Function --------------------
a = 2
b = -8
c = 3

def f(x):
    return a * x**2 + b * x + c

# -------------------- Vertex by Completing the Square --------------------
vertex_x = -b / (2 * a)
vertex_y = f(vertex_x)
vertex = (vertex_x, vertex_y)

# -------------------- Gradient Descent Method --------------------
x_gd = 0.0
lr = 0.1
eps = 1e-6
max_iter = 1000

def grad(x):
    return 2 * a * x + b

trajectory = [x_gd]

for _ in range(max_iter):
    x_new = x_gd - lr * grad(x_gd)
    trajectory.append(x_new)
    if abs(x_new - x_gd) < eps:
        break
    x_gd = x_new

x_gd_final = x_gd
y_gd_final = f(x_gd_final)

# -------------------- Plotting --------------------
x_vals = np.linspace(vertex_x - 5, vertex_x + 5, 400)
y_vals = f(x_vals)

plt.figure(figsize=(10, 6))
plt.plot(x_vals, y_vals, label='y = ax² + bx + c')
plt.plot(vertex_x, vertex_y, 'ro', label=f'Vertex (x={vertex_x:.2f}, y={vertex_y:.2f})')
plt.plot(x_gd_final, y_gd_final, 'go', label=f'Min (GD x={x_gd_final:.2f}, y={y_gd_final:.2f})')
plt.plot(trajectory, [f(x) for x in trajectory], 'g--', alpha=0.5, label='Descent path')
plt.title('Comparison: Completing the Square vs Gradient Descent')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True)
plt.show()

# -------------------- Numerical Output --------------------
print("【平方完成】Vertex by completing the square:")
print(f"x = {vertex_x:.6f}, y = {vertex_y:.6f}")

print("\n【勾配法】Minimum by gradient descent:")
print(f"x = {x_gd_final:.6f}, y = {y_gd_final:.6f}")
print(f"Steps: {len(trajectory)-1}")


```
三角関数
```python
import numpy as np
import matplotlib.pyplot as plt

# 度数とラジアンへの変換 / Degrees and radians
degrees = np.arange(0, 361, 1)  # 0度〜360度 / 0° to 360°
radians = np.radians(degrees)  # ラジアンに変換 / Convert to radians

# 三角関数の計算 / Compute trigonometric values
sin_vals = np.sin(radians)
cos_vals = np.cos(radians)
tan_vals = np.tan(radians)

# 表示 / Print values
print("角度°   sin     cos     tan")
for deg, s, c, t in zip(degrees, sin_vals, cos_vals, tan_vals):
    if abs(c) < 1e-10:
        print(f"{deg:3}°  {s:>6.3f}  {c:>6.3f}   {'undefined':>8}")
    else:
        print(f"{deg:3}°  {s:>6.3f}  {c:>6.3f}   {t:>8.3f}")

# プロット / Plotting
plt.figure(figsize=(12, 6))
plt.plot(degrees, sin_vals, label='sin(θ)')
plt.plot(degrees, cos_vals, label='cos(θ)')
plt.plot(degrees, tan_vals, label='tan(θ)', linestyle='--')
plt.ylim(-2, 2)  # tanの発散を避けるため範囲制限 / Limit y-axis for tan
plt.title('Trigonometric Functions (0° to 360°)')
plt.xlabel('Degree (°)')
plt.ylabel('Function Value')
plt.legend()
plt.grid(True)
plt.show()


```

連立方程式
```python
# Program Name: solve_linear_system_combined.py  
# Creation Date: 20250603  
# Overview: Solve 3x3 linear system using both direct solver and LU decomposition  
# Usage: Run in Python environment with numpy and scipy installed  

# -------------------- Install Required Libraries --------------------


# -------------------- Import Libraries --------------------
import numpy as np
from scipy.linalg import lu

# -------------------- Define Coefficient Matrix and Constant Vector --------------------
# 係数行列 A / Coefficient matrix
A = np.array([
    [1, -1, 1],   # 式1: a - b + c = -2
    [1,  1, 1],   # 式2: a + b + c = 6
    [4,  2, 1]    # 式3: 4a + 2b + c = 7
])

# 定数ベクトル B / Constant vector
B = np.array([-2, 6, 7])

# -------------------- Method 1: Direct Solve --------------------
# NumPy の solve 関数で直接解く / Solve Ax = B directly
x_direct = np.linalg.solve(A, B)
a1, b1, c1 = x_direct

print("=== Solution by Direct Method (NumPy) ===")
print(f"a = {a1:.2f}, b = {b1:.2f}, c = {c1:.2f}")

# -------------------- Method 2: LU Decomposition --------------------
# LU分解 / LU decomposition
P, L, U = lu(A)

# 右辺ベクトルを変換（PB）/ Adjust RHS using permutation matrix P
PB = np.dot(P, B)

# Ly = PB を解く / Solve Ly = PB
y = np.linalg.solve(L, PB)

# Ux = y を解く / Solve Ux = y
x_lu = np.linalg.solve(U, y)
a2, b2, c2 = x_lu

# -------------------- Display LU Decomposition and Solution --------------------
print("\n=== LU Decomposition ===")
print("P matrix:\n", P)
print("L matrix:\n", L)
print("U matrix:\n", U)

print("\n=== Solution by LU Decomposition ===")
print(f"a = {a2:.2f}, b = {b2:.2f}, c = {c2:.2f}")


```


```python
# Program Name: trig_identity_verification.py  
# Creation Date: 20250603  
# Overview: Verify trigonometric identities involving tan, cos, and sin using symbolic computation  
# Usage: Run in Python environment with sympy installed  

# -------------------- Install Required Libraries --------------------


# -------------------- Import Libraries --------------------
import sympy as sp

# -------------------- Define Symbol --------------------
theta = sp.symbols('theta', real=True)

# -------------------- Identity 1: 1 + tan²θ = 1 / cos²θ --------------------
lhs1 = 1 + sp.tan(theta)**2           # 左辺 / Left-hand side
rhs1 = 1 / sp.cos(theta)**2           # 右辺 / Right-hand side
identity1 = sp.simplify(lhs1 - rhs1)  # 恒等式差分が0になるか検証 / Verify identity

# -------------------- Identity 2: 1 + 1 / tan²θ = 1 / sin²θ --------------------
lhs2 = 1 + 1 / sp.tan(theta)**2       # 左辺 / Left-hand side
rhs2 = 1 / sp.sin(theta)**2           # 右辺 / Right-hand side
identity2 = sp.simplify(lhs2 - rhs2)  # 恒等式差分が0になるか検証 / Verify identity

# -------------------- Display Results --------------------
print("=== Identity Verification ===")
print("1 + tan²θ = 1 / cos²θ →", "OK" if identity1 == 0 else "NG")
print("1 + 1 / tan²θ = 1 / sin²θ →", "OK" if identity2 == 0 else "NG")


```
```python

# Program Name: cosine_substitution_plot.py  
# Creation Date: 20250603  
# Overview: Compare original trig function and substitution quadratic function  
# Usage: Run in Python environment with numpy and matplotlib installed  

# -------------------- Install Required Libraries --------------------


# -------------------- Import Libraries --------------------
import numpy as np
import matplotlib.pyplot as plt

# -------------------- Define Domain --------------------
x = np.linspace(0, 2 * np.pi, 400)  # x の定義（0〜2π）
t = np.linspace(-1, 1, 400)         # t = cos(x) の定義域は [-1, 1]

# -------------------- Define Functions --------------------
y1 = -np.cos(x)**2 - np.cos(x) + 1  # y = -cos²x - cosx + 1
y2 = -t**2 - t + 1                  # y = -t² - t + 1

# -------------------- Plot Comparison --------------------
plt.figure(figsize=(10, 5))

# グラフ①：元の三角関数 / Original trigonometric function
plt.subplot(1, 2, 1)
plt.plot(x, y1, label=r"$y = -\cos^2 x - \cos x + 1$")
plt.title("y as a function of x")
plt.xlabel("x")
plt.ylabel("y")
plt.grid(True)
plt.legend()

# グラフ②：代入後の2次関数 / Substitution function
plt.subplot(1, 2, 2)
plt.plot(t, y2, label=r"$y = -t^2 - t + 1$", color="orange")
plt.title("y as a function of t (t = cos x)")
plt.xlabel("t")
plt.ylabel("y")
plt.grid(True)
plt.legend()

plt.tight_layout()
plt.show()

```


```python
# Program Name: law_of_sines_and_cosines_numeric.py  
# Creation Date: 20250603  
# Overview: Compute and verify Law of Sines and Cosines numerically with triangle ABC  
# Usage: Run in Python environment with numpy and sympy installed  

# -------------------- Install Required Libraries --------------------

# -------------------- Import Libraries --------------------
import numpy as np
import sympy as sp

# -------------------- Define Angles and Sides --------------------
# 三角形ABC：角A, B, C（度）と辺a, b, c（数値） / Define angles in degrees and sides in units
A_deg, B_deg, C_deg = 50, 60, 70  # 角度 / Angles in degrees
a, b, c = 8, 9, 10                # 辺の長さ / Side lengths

# -------------------- Convert Degrees to Radians --------------------
A = np.radians(A_deg)
B = np.radians(B_deg)
C = np.radians(C_deg)

# -------------------- Law of Sines Check --------------------
# a/sinA ≈ b/sinB ≈ c/sinC
ratio_a = a / np.sin(A)
ratio_b = b / np.sin(B)
ratio_c = c / np.sin(C)

print("=== Law of Sines Check ===")
print(f"a / sin A = {ratio_a:.4f}")
print(f"b / sin B = {ratio_b:.4f}")
print(f"c / sin C = {ratio_c:.4f}")

# -------------------- Law of Cosines Check --------------------
# 余弦定理でA, B, Cを逆算 / Verify A from cosine rule: cos A = (b² + c² - a²) / 2bc
cos_A_calc = (b**2 + c**2 - a**2) / (2 * b * c)
cos_B_calc = (c**2 + a**2 - b**2) / (2 * c * a)
cos_C_calc = (a**2 + b**2 - c**2) / (2 * a * b)

print("\n=== Law of Cosines Check ===")
print(f"cos A (from sides) = {cos_A_calc:.4f}, actual = {np.cos(A):.4f}")
print(f"cos B (from sides) = {cos_B_calc:.4f}, actual = {np.cos(B):.4f}")
print(f"cos C (from sides) = {cos_C_calc:.4f}, actual = {np.cos(C):.4f}")


```


```python

# Program Name: triangle_area_formulae.py  
# Creation Date: 20250603  
# Overview: Compute triangle area using sine formula and Heron's formula  
# Usage: Run in Python environment with numpy and math installed  

# -------------------- Install Required Libraries --------------------

# -------------------- Import Libraries --------------------
import numpy as np
import math

# -------------------- Define Triangle Sides and Angle --------------------
a, b, c = 8, 9, 10             # 三角形の3辺 / Side lengths
C_deg = 70                    # 角C（度）/ Angle C in degrees

# -------------------- Convert Angle to Radians --------------------
C_rad = np.radians(C_deg)     # 角Cをラジアンに変換 / Convert angle to radians

# -------------------- Method 1: Sine Formula --------------------
# S = 1/2 * ab * sin C
area_sine = 0.5 * a * b * np.sin(C_rad)

# -------------------- Method 2: Heron's Formula --------------------
# s = (a + b + c) / 2
s = (a + b + c) / 2

# S = √(s(s - a)(s - b)(s - c))
area_heron = math.sqrt(s * (s - a) * (s - b) * (s - c))

# -------------------- Display Results --------------------
print("=== Triangle Area Calculation ===")
print(f"Using Sine Formula: S = {area_sine:.4f}")
print(f"Using Heron's Formula: S = {area_heron:.4f}")

```


```python

# Program Name: gcd_lcm_calculator.py  
# Creation Date: 20250603  
# Overview: Calculate GCD (最大公約数) and LCM (最小公倍数) of two integers  
# Usage: Run in Python environment with math installed  

# -------------------- Install Required Libraries --------------------
# mathモジュールは標準ライブラリのためインストール不要 / No need to install

# -------------------- Import Libraries --------------------
import math

# -------------------- Define Two Integers --------------------
a = 36
b = 60

# -------------------- Compute GCD --------------------
# 最大公約数 / Greatest Common Divisor
gcd = math.gcd(a, b)

# -------------------- Compute LCM --------------------
# 最小公倍数 / Least Common Multiple: LCM(a, b) = abs(a*b) // GCD(a, b)
lcm = abs(a * b) // gcd

# -------------------- Display Results --------------------
print("=== GCD & LCM Calculation ===")
print(f"a = {a}, b = {b}")
print(f"GCD (最大公約数) = {gcd}")
print(f"LCM (最小公倍数) = {lcm}")

```