0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

多変数関数の最大・最小パターン

Posted at
# -*- coding: utf-8 -*-
# Program Name: lagrange_minimization_analytic_visual.py
# Creation Date: 20250111
# Overview: Symbolic and numerical minimization with plotting
# Usage: Run with `python lagrange_minimization_analytic_visual.py`

# --- Install required libraries / 必要なライブラリのインストール ---
# !pip install numpy matplotlib scipy sympy

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import minimize
import sympy as sp

# -----------------------------
# Problem (1) Analytic Solution
# x + 2y = 5, minimize x^2 + y^2

# SymPy symbolic variables / 記号変数定義
x, y, λ = sp.symbols('x y λ')

# Lagrangian / ラグランジュ関数
L = x**2 + y**2 - λ * (x + 2*y - 5)

# Stationary conditions / 停留条件
grad_L = [sp.diff(L, var) for var in (x, y, λ)]
solution_1 = sp.solve(grad_L, (x, y, λ))

x_val_1 = solution_1[x]
y_val_1 = solution_1[y]
min_val_1 = x_val_1**2 + y_val_1**2

print("\n--- Problem (1) Analytic Solution ---")
print(f"x = {sp.simplify(x_val_1)}")
print(f"y = {sp.simplify(y_val_1)}")
print(f"Minimum value = {sp.simplify(min_val_1)}")

# -----------------------------
# Problem (1) Geometric Visualization / 可視化
x_line = np.linspace(-10, 10, 400)
y_line = (5 - x_line) / 2

plt.plot(x_line, y_line, label="x + 2y = 5")
plt.scatter([float(x_val_1)], [float(y_val_1)], color="red", label="Minimum Point")
plt.title("Problem (1): Minimizing x^2 + y^2 with x + 2y = 5")
plt.xlabel("x")
plt.ylabel("y")
plt.axis("equal")
plt.legend()
plt.show()

# -----------------------------
# Problem (2) Analytic Solution
# x + y + 2z = 1, x - 3y + 4z = 1, minimize x^2 + y^2 + z^2

# Symbolic variables / 記号変数定義
x, y, z, λ1, λ2 = sp.symbols('x y z λ1 λ2')

# Lagrangian / ラグランジュ関数
L2 = x**2 + y**2 + z**2 - λ1 * (x + y + 2*z - 1) - λ2 * (x - 3*y + 4*z - 1)

# Stationary conditions / 停留条件
grad_L2 = [sp.diff(L2, var) for var in (x, y, z, λ1, λ2)]
solution_2 = sp.solve(grad_L2, (x, y, z, λ1, λ2))

x_val_2 = solution_2[x]
y_val_2 = solution_2[y]
z_val_2 = solution_2[z]
min_val_2 = x_val_2**2 + y_val_2**2 + z_val_2**2

print("\n--- Problem (2) Analytic Solution ---")
print(f"x = {sp.simplify(x_val_2)}")
print(f"y = {sp.simplify(y_val_2)}")
print(f"z = {sp.simplify(z_val_2)}")
print(f"Minimum value = {sp.simplify(min_val_2)}")

# -*- coding: utf-8 -*-
# Program Name: inequality_max_min_analytic.py
# Creation Date: 20250111
# Overview: Analytic solution using SymPy (fractional output)
# Usage: Run with `python inequality_max_min_analytic.py`

# --- Install required libraries ---
# !pip install sympy matplotlib numpy

import sympy as sp
import numpy as np
import matplotlib.pyplot as plt

# -----------------------------
# Problem (1) Analytic Solution
x, y = sp.symbols('x y', real=True, nonnegative=True)

# Constraint: 2x + y = 8
y_expr = 8 - 2 * x

# Objective: xy
xy_expr = x * y_expr

# Expand and differentiate
xy_derivative = sp.diff(xy_expr, x)

# Solve for critical points
critical_x = sp.solve(xy_derivative, x)
critical_y = [y_expr.subs(x, val) for val in critical_x]
critical_xy = [xy_expr.subs(x, val) for val in critical_x]

# Evaluate boundary at x = 0 and x = 4
boundary_points = [0, 4]
boundary_y = [y_expr.subs(x, val) for val in boundary_points]
boundary_xy = [xy_expr.subs(x, val) for val in boundary_points]

# Collect all candidates
candidates = list(zip(critical_x + boundary_points, critical_y + boundary_y, critical_xy + boundary_xy))

# Display Results
print("\n--- Problem (1) Analytic Candidates ---")
for idx, (xi, yi, xyi) in enumerate(candidates, 1):
    print(f"Candidate {idx}: x = {sp.simplify(xi)}, y = {sp.simplify(yi)}, xy = {sp.simplify(xyi)}")

# -----------------------------
# Problem (2) Analytic Solution
# Objective: x^2 y^2 + 4x^2 + y^2
g_expr = x**2 * y_expr**2 + 4 * x**2 + y_expr**2

# Differentiate and solve
g_derivative = sp.diff(g_expr, x)
critical_x_g = sp.solve(g_derivative, x)

# Evaluate candidates
critical_y_g = [y_expr.subs(x, val) for val in critical_x_g]
critical_g = [g_expr.subs(x, val) for val in critical_x_g]

# Evaluate boundary at x = 0 and x = 4
boundary_y_g = [y_expr.subs(x, val) for val in boundary_points]
boundary_g = [g_expr.subs(x, val) for val in boundary_points]

# Collect all candidates
candidates_g = list(zip(critical_x_g + boundary_points, critical_y_g + boundary_y_g, critical_g + boundary_g))

# Display Results
print("\n--- Problem (2) Analytic Candidates ---")
for idx, (xi, yi, gi) in enumerate(candidates_g, 1):
    print(f"Candidate {idx}: x = {sp.simplify(xi)}, y = {sp.simplify(yi)}, g(x,y) = {sp.simplify(gi)}")

# -----------------------------
# Optional Visualization
x_vals = np.linspace(0, 4, 100)
y_vals = 8 - 2 * x_vals
xy_vals = x_vals * y_vals
g_vals = x_vals**2 * y_vals**2 + 4 * x_vals**2 + y_vals**2

plt.plot(x_vals, xy_vals, label="xy = x(8 - 2x)")
plt.title("Problem (1) xy Plot")
plt.xlabel("x")
plt.ylabel("xy")
plt.legend()
plt.show()

plt.plot(x_vals, g_vals, label="g(x,y) = x^2 y^2 + 4x^2 + y^2")
plt.title("Problem (2) g(x,y) Plot")
plt.xlabel("x")
plt.ylabel("g(x,y)")
plt.legend()
plt.show()

# -*- coding: utf-8 -*-
# Program Name: symbolic_max_min_solver.py
# Creation Date: 20250111
# Overview: Solves maximum and minimum problems analytically using SymPy
# Usage: Run with `python symbolic_max_min_solver.py`

# --- Install required libraries ---
# !pip install sympy

import sympy as sp

# -----------------------------
# Problem (1) Analytic Solution
x, y, λ = sp.symbols('x y λ')

# Lagrangian definition / ラグランジュ関数定義
L1 = 2 * x + y**2 - λ * (2 * x**2 + y**2 - 2)

# Stationary conditions / 停留条件
grad_L1 = [sp.diff(L1, var) for var in (x, y, λ)]
solution1 = sp.solve(grad_L1, (x, y, λ), dict=True)

print("\n--- Problem (1) Analytic Solutions ---")
for sol in solution1:
    val = 2 * sol[x] + sol[y]**2
    print(f"x = {sp.simplify(sol[x])}, y = {sp.simplify(sol[y])}, Value = {sp.simplify(val)}")

# -----------------------------
# Problem (2) Analytic Solution
x, y, λ = sp.symbols('x y λ')

# Lagrangian definition / ラグランジュ関数定義
L2 = x**2 + 2 * y**2 + 6 * y - λ * (x**2 + y**2 + 2 * y - 3)

# Stationary conditions / 停留条件
grad_L2 = [sp.diff(L2, var) for var in (x, y, λ)]
solution2 = sp.solve(grad_L2, (x, y, λ), dict=True)

print("\n--- Problem (2) Analytic Solutions ---")
for sol in solution2:
    val = sol[x]**2 + 2 * sol[y]**2 + 6 * sol[y]
    print(f"x = {sp.simplify(sol[x])}, y = {sp.simplify(sol[y])}, Value = {sp.simplify(val)}")

# -*- coding: utf-8 -*-
# Program Name: unconstrained_and_bounded_optimization.py
# Creation Date: 20250111
# Overview: Analytically solve unconstrained and bounded optimization problems.
# Usage: Run with `python unconstrained_and_bounded_optimization.py`

# --- Install required libraries ---
# !pip install sympy scipy numpy matplotlib

import sympy as sp
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import minimize_scalar

# -----------------------------
# Problem (1): Unconstrained Minimization / 無制約最小化
x, y = sp.symbols('x y')
f = x**2 + 2*x + y**2 - 4*y + 1

# Gradient and Stationary Point / 勾配と停留点
grad_f = [sp.diff(f, var) for var in (x, y)]
stationary_point = sp.solve(grad_f, (x, y), dict=True)

print("\n--- Problem (1) Unconstrained Minimization ---")
for sol in stationary_point:
    val = f.subs(sol)
    print(f"x = {sol[x]}, y = {sol[y]}, Minimum Value = {sp.simplify(val)}")

# -----------------------------
# Problem (2): Bounded Maximization and Minimization / 有界最適化
f_func = sp.lambdify((x, y), f, 'numpy')

x_bounds = np.linspace(1, 3, 100)
y_bounds = np.linspace(-1, 4, 100)
X, Y = np.meshgrid(x_bounds, y_bounds)
Z = f_func(X, Y)

max_val = np.max(Z)
min_val = np.min(Z)
max_loc = np.unravel_index(np.argmax(Z), Z.shape)
min_loc = np.unravel_index(np.argmin(Z), Z.shape)

print("\n--- Problem (2) Bounded Optimization ---")
print(f"Maximum Value: {max_val:.4f} at x = {X[max_loc]:.4f}, y = {Y[max_loc]:.4f}")
print(f"Minimum Value: {min_val:.4f} at x = {X[min_loc]:.4f}, y = {Y[min_loc]:.4f}")

plt.contourf(X, Y, Z, levels=50)
plt.colorbar()
plt.scatter([X[max_loc]], [Y[max_loc]], color='red', label="Maximum")
plt.scatter([X[min_loc]], [Y[min_loc]], color='blue', label="Minimum")
plt.title("Problem (2) Bounded Optimization")
plt.xlabel("x")
plt.ylabel("y")
plt.legend()
plt.show()

# -----------------------------
# Problem (3): Unconstrained Minimization / 無制約最小化
g = x**2 + 2*x*y + 2*y**2 + 4*x - 2*y + 1
grad_g = [sp.diff(g, var) for var in (x, y)]
stationary_point_g = sp.solve(grad_g, (x, y), dict=True)

print("\n--- Problem (3) Unconstrained Minimization ---")
for sol in stationary_point_g:
    val = g.subs(sol)
    print(f"x = {sp.simplify(sol[x])}, y = {sp.simplify(sol[y])}, Minimum Value = {sp.simplify(val)}")

# -*- coding: utf-8 -*-
# Program Name: constraint_optimization_examples.py
# Creation Date: 20250111
# Overview: Analytical solutions to constrained optimization problems using SymPy
# Usage: Run with `python constraint_optimization_examples.py`

# --- Install required libraries ---
# !pip install sympy

import sympy as sp

# -----------------------------
# Problem (1)
x, y, λ = sp.symbols('x y λ', positive=True)
L1 = 2 * x + y - λ * (x * y - 4)
grad_L1 = [sp.diff(L1, var) for var in (x, y, λ)]
solution1 = sp.solve(grad_L1, (x, y, λ), dict=True)

print("\n--- Problem (1) Solution ---")
for sol in solution1:
    val = 2 * sol[x] + sol[y]
    print(f"x = {sp.simplify(sol[x])}, y = {sp.simplify(sol[y])}, Minimum Value = {sp.simplify(val)}")

# -----------------------------
# Problem (2)
x, y, λ = sp.symbols('x y λ', positive=True)
L2 = x * y - λ * (2 * x + y - 4)
grad_L2 = [sp.diff(L2, var) for var in (x, y, λ)]
solution2 = sp.solve(grad_L2, (x, y, λ), dict=True)

print("\n--- Problem (2) Solution ---")
for sol in solution2:
    val = sol[x] * sol[y]
    print(f"x = {sp.simplify(sol[x])}, y = {sp.simplify(sol[y])}, Maximum Value = {sp.simplify(val)}")

# -----------------------------
# Problem (3)
x, y, z, λ = sp.symbols('x y z λ', positive=True)
L3 = x * y * z - λ * (x + y + z - 12)
grad_L3 = [sp.diff(L3, var) for var in (x, y, z, λ)]
solution3 = sp.solve(grad_L3, (x, y, z, λ), dict=True)

print("\n--- Problem (3) Solution ---")
for sol in solution3:
    val = sol[x] * sol[y] * sol[z]
    print(f"x = {sp.simplify(sol[x])}, y = {sp.simplify(sol[y])}, z = {sp.simplify(sol[z])}, Maximum Volume = {sp.simplify(val)}")

# -*- coding: utf-8 -*-
# Program Name: lagrange_optimization_symbolic.py
# Creation Date: 20250111
# Overview: Symbolic solutions for optimization problems with equality constraints
# Usage: Run with `python lagrange_optimization_symbolic.py`

# --- Install required libraries ---
# !pip install sympy

import sympy as sp

# -----------------------------
# Problem (1) Max/Min of 2x + y with x^2 + y^2 = 4
x, y, λ = sp.symbols('x y λ')
L1 = 2 * x + y - λ * (x**2 + y**2 - 4)
grad_L1 = [sp.diff(L1, var) for var in (x, y, λ)]
sol1 = sp.solve(grad_L1, (x, y, λ), dict=True)

print("\n--- Problem (1) Max/Min of 2x + y ---")
for s in sol1:
    val = 2 * s[x] + s[y]
    print(f"x = {sp.simplify(s[x])}, y = {sp.simplify(s[y])}, Value = {sp.simplify(val)}")

# -----------------------------
# Problem (2) Min of x^2 + 4y^2 with x + y = 5
x, y, λ = sp.symbols('x y λ')
L2 = x**2 + 4 * y**2 - λ * (x + y - 5)
grad_L2 = [sp.diff(L2, var) for var in (x, y, λ)]
sol2 = sp.solve(grad_L2, (x, y, λ), dict=True)

print("\n--- Problem (2) Min of x^2 + 4y^2 ---")
for s in sol2:
    val = s[x]**2 + 4 * s[y]**2
    print(f"x = {sp.simplify(s[x])}, y = {sp.simplify(s[y])}, Minimum Value = {sp.simplify(val)}")

# -----------------------------
# Problem (3) Min of x^2 + y^2 + z^2 with x + 2y + 3z = 7
x, y, z, λ = sp.symbols('x y z λ')
L3 = x**2 + y**2 + z**2 - λ * (x + 2 * y + 3 * z - 7)
grad_L3 = [sp.diff(L3, var) for var in (x, y, z, λ)]
sol3 = sp.solve(grad_L3, (x, y, z, λ), dict=True)

print("\n--- Problem (3) Min of x^2 + y^2 + z^2 ---")
for s in sol3:
    val = s[x]**2 + s[y]**2 + s[z]**2
    print(f"x = {sp.simplify(s[x])}, y = {sp.simplify(s[y])}, z = {sp.simplify(s[z])}, Minimum Value = {sp.simplify(val)}")

# -*- coding: utf-8 -*-
# Program Name: advanced_optimization_sympy.py
# Creation Date: 20250111
# Overview: Symbolic maximization and minimization with multiple constraints
# Usage: Run with `python advanced_optimization_sympy.py`

# --- Install required libraries ---
# !pip install sympy

import sympy as sp

# -----------------------------
# Problem (1)
x, y, λ = sp.symbols('x y λ')
L1 = x * y + x + y - λ * (x**2 - x * y + y**2 - 1)
grad_L1 = [sp.diff(L1, var) for var in (x, y, λ)]
sol1 = sp.solve(grad_L1, (x, y, λ), dict=True)

print("\n--- Problem (1) Max/Min of xy + x + y ---")
for s in sol1:
    val = s[x] * s[y] + s[x] + s[y]
    print(f"x = {sp.simplify(s[x])}, y = {sp.simplify(s[y])}, Value = {sp.simplify(val)}")

# -----------------------------
# Problem (2)
x, y, z, λ1, λ2 = sp.symbols('x y z λ1 λ2')
L2 = x**3 + y**3 + z**3 - λ1 * (x + y + z - 2) - λ2 * (x**2 + y**2 + z**2 - 2)
grad_L2 = [sp.diff(L2, var) for var in (x, y, z, λ1, λ2)]
sol2 = sp.solve(grad_L2, (x, y, z, λ1, λ2), dict=True)

print("\n--- Problem (2) Max/Min of x^3 + y^3 + z^3 ---")
for s in sol2:
    val = s[x]**3 + s[y]**3 + s[z]**3
    print(f"x = {sp.simplify(s[x])}, y = {sp.simplify(s[y])}, z = {sp.simplify(s[z])}, Value = {sp.simplify(val)}")

# -----------------------------
# Problem (3)
x, y, z, λ1, λ2 = sp.symbols('x y z λ1 λ2')
L3 = x * y * z - λ1 * (x + y + z - 6) - λ2 * (2 * (x * y + y * z + z * x) - 18)
grad_L3 = [sp.diff(L3, var) for var in (x, y, z, λ1, λ2)]
sol3 = sp.solve(grad_L3, (x, y, z, λ1, λ2), dict=True)

print("\n--- Problem (3) Max Volume with Fixed Perimeter and Surface Area ---")
for s in sol3:
    val = s[x] * s[y] * s[z]
    print(f"x = {sp.simplify(s[x])}, y = {sp.simplify(s[y])}, z = {sp.simplify(s[z])}, Volume = {sp.simplify(val)}")

# -*- coding: utf-8 -*-
# Program Name: inequality_constraints_optimization.py
# Creation Date: 20250111
# Overview: Numerical solution for inequality constrained optimization using scipy
# Usage: Run with `python inequality_constraints_optimization.py`

# --- Install required libraries ---
# !pip install numpy scipy

import numpy as np
from scipy.optimize import minimize

# -----------------------------
# 共通制約条件 / Common Constraints
def constraint1(vars):
    x, y = vars
    return x + 2 * y - 4  # x + 2y >= 4

def constraint2(vars):
    x, y = vars
    return x - 3 * y + 6  # x - 3y >= -6  <=> x - 3y + 6 >= 0

def constraint3(vars):
    x, y = vars
    return 12 - 3 * x - y  # 3x + y <= 12  <=> 12 - 3x - y >= 0

constraints = [{'type': 'ineq', 'fun': constraint1},
               {'type': 'ineq', 'fun': constraint2},
               {'type': 'ineq', 'fun': constraint3}]

# -----------------------------
# Utility function to run min/max
def optimize_objective(func, bounds=(-100, 100)):
    result_min = minimize(func, x0=np.array([0.0, 0.0]), constraints=constraints)
    result_max = minimize(lambda vars: -func(vars), x0=np.array([0.0, 0.0]), constraints=constraints)
    return result_min, result_max

# -----------------------------
# Problem (1) Max/Min of 2x + y
def objective1(vars):
    x, y = vars
    return 2 * x + y

min1, max1 = optimize_objective(objective1)

# -----------------------------
# Problem (2) Min/Max of x^2 + y^2
def objective2(vars):
    x, y = vars
    return x**2 + y**2

min2, max2 = optimize_objective(objective2)

# -----------------------------
# Problem (3) Min/Max of (y - 1) / (x + 1)
def objective3(vars):
    x, y = vars
    if x + 1 == 0:
        return np.inf
    return (y - 1) / (x + 1)

min3, max3 = optimize_objective(objective3)

# -----------------------------
# Result Display
def display_results(label, min_res, max_res):
    print(f"\n--- {label} ---")
    print(f"Minimum: {min_res.fun:.4f} at x = {min_res.x[0]:.4f}, y = {min_res.x[1]:.4f}")
    print(f"Maximum: {-max_res.fun:.4f} at x = {max_res.x[0]:.4f}, y = {max_res.x[1]:.4f}")

display_results("Problem (1) 2x + y", min1, max1)
display_results("Problem (2) x^2 + y^2", min2, max2)
display_results("Problem (3) (y - 1) / (x + 1)", min3, max3)

# -*- coding: utf-8 -*-
# Program Name: lagrange_quadratic_optimization.py
# Creation Date: 20250111
# Overview: Symbolic maximization and minimization with quadratic equality constraints
# Usage: Run with `python lagrange_quadratic_optimization.py`

# --- Install required libraries ---
# !pip install sympy

import sympy as sp

# -----------------------------
# Problem (1)
x, y, λ = sp.symbols('x y λ')
# Objective function / 目的関数
f1 = x**2 + 2 * x * y + 3 * y**2
# Constraint / 制約条件
constraint1 = x**2 + y**2 - 1
# Lagrangian / ラグランジュ関数
L1 = f1 - λ * constraint1

# Gradient and Stationary Conditions / 勾配と停留条件
grad_L1 = [sp.diff(L1, var) for var in (x, y, λ)]
sol1 = sp.solve(grad_L1, (x, y, λ), dict=True)

print("\n--- Problem (1) Max/Min of x^2 + 2xy + 3y^2 ---")
for s in sol1:
    val = f1.subs(s)
    print(f"x = {sp.simplify(s[x])}, y = {sp.simplify(s[y])}, Value = {sp.simplify(val)}")

# -----------------------------
# Problem (2)
x, y, λ = sp.symbols('x y λ')
# Objective function / 目的関数
f2 = 2 * x**2 + x * y + 4 * y**2
# Constraint / 制約条件
constraint2 = 4 * x**2 + 9 * y**2 - 36
# Lagrangian / ラグランジュ関数
L2 = f2 - λ * constraint2

# Gradient and Stationary Conditions / 勾配と停留条件
grad_L2 = [sp.diff(L2, var) for var in (x, y, λ)]
sol2 = sp.solve(grad_L2, (x, y, λ), dict=True)

print("\n--- Problem (2) Max/Min of 2x^2 + xy + 4y^2 ---")
for s in sol2:
    val = f2.subs(s)
    print(f"x = {sp.simplify(s[x])}, y = {sp.simplify(s[y])}, Value = {sp.simplify(val)}")

# -*- coding: utf-8 -*-
# Program Name: quadratic_fraction_optimization.py
# Creation Date: 20250111
# Overview: Solves equality and bounded optimization problems using SymPy and SciPy
# Usage: Run with `python quadratic_fraction_optimization.py`

# --- Install required libraries ---
# !pip install sympy numpy scipy

import sympy as sp
import numpy as np
from scipy.optimize import minimize

# -----------------------------
# Problem (1) Quadratic Constraint Optimization
x, y, λ = sp.symbols('x y λ')
# Objective / 目的関数
f1 = x**2 + y**2
# Constraint / 制約条件
constraint1 = 4 * x**2 - 8 * x * y + 10 * y**2 - 1
# Lagrangian / ラグランジュ関数
L1 = f1 - λ * constraint1

# Stationary Conditions / 勾配と停留条件
grad_L1 = [sp.diff(L1, var) for var in (x, y, λ)]
sol1 = sp.solve(grad_L1, (x, y, λ), dict=True)

print("\n--- Problem (1) Max/Min of x^2 + y^2 ---")
for s in sol1:
    val = f1.subs(s)
    print(f"x = {sp.simplify(s[x])}, y = {sp.simplify(s[y])}, Value = {sp.simplify(val)}")

# -----------------------------
# Problem (2) Bounded Fractional Optimization
def fractional_objective(vars):
    x, y = vars
    numerator = 2 * x * y
    denominator = 4 * x**2 + y**2
    if denominator == 0:
        return -np.inf
    return - numerator / denominator  # Negative for maximization

bounds = [(1, 2), (2, 4)]
initial_guess = [1.5, 3]

result = minimize(fractional_objective, initial_guess, bounds=bounds)

# Convert back to maximization result
max_value = -result.fun
x_opt, y_opt = result.x

print("\n--- Problem (2) Maximum of 2xy / (4x^2 + y^2) ---")
print(f"Maximum Value: {max_value:.4f} at x = {x_opt:.4f}, y = {y_opt:.4f}")

# -*- coding: utf-8 -*-
# Program Name: bounded_and_constrained_optimization.py
# Creation Date: 20250111
# Overview: Numerical solution of bounded and inequality constrained optimization problems
# Usage: Run with `python bounded_and_constrained_optimization.py`

# --- Install required libraries ---
# !pip install numpy scipy

import numpy as np
from scipy.optimize import minimize

# -----------------------------
# Problem (1)
def objective1(vars):
    x, y = vars
    return x * y + x - 2 * y + 1  # 正しいreturn文に修正

bounds1 = [(3, 4), (-2, 0)]
result_min1 = minimize(objective1, [3.5, -1], bounds=bounds1)
result_max1 = minimize(lambda v: -objective1(v), [3.5, -1], bounds=bounds1)

# -----------------------------
# Problem (2)
def objective2(vars):
    x, y = vars
    return x**2 - y**2

constraints2 = [
    {'type': 'ineq', 'fun': lambda v: v[0] + 2 * v[1] - 4},
    {'type': 'ineq', 'fun': lambda v: v[0] - 3 * v[1] + 6},
    {'type': 'ineq', 'fun': lambda v: 12 - 3 * v[0] - v[1]}
]

result_min2 = minimize(objective2, [1.0, 1.0], constraints=constraints2)
result_max2 = minimize(lambda v: -objective2(v), [1.0, 1.0], constraints=constraints2)

# -----------------------------
# Problem (3)
def objective3(vars):
    x, y, z = vars
    return x**2 + y**2 + z**2 - x * y - y * z - z * x

bounds3 = [(0, 1), (1, 2), (2, 3)]
result_min3 = minimize(objective3, [0.5, 1.5, 2.5], bounds=bounds3)

# -----------------------------
# Result Display Function
def display(label, result_min, result_max=None):
    print(f"\n--- {label} ---")
    print(f"Minimum: {result_min.fun:.4f} at x = {result_min.x}")
    if result_max:
        print(f"Maximum: {-result_max.fun:.4f} at x = {result_max.x}")

display("Problem (1) xy + x - 2y + 1", result_min1, result_max1)
display("Problem (2) x^2 - y^2", result_min2, result_max2)
display("Problem (3) x^2 + y^2 + z^2 - xy - yz - zx", result_min3)

# -*- coding: utf-8 -*-
# Program Name: lagrange_fraction_optimization.py
# Creation Date: 20250111
# Overview: Symbolic maximization and minimization with linear equality constraints
# Usage: Run with `python lagrange_fraction_optimization.py`

# --- Install required libraries ---
# !pip install sympy

import sympy as sp

# -----------------------------
# 共通設定
x, y, λ = sp.symbols('x y λ')
f = x**2 - 2 * x * y + 2 * y**2  # 目的関数

# 検討する等式制約のリスト
constraints = [
    x - 2 * y + 3,  # x - 2y = -3
    x - 2 * y - 4,  # x - 2y = 4
    2 * x - y - 3,  # 2x - y = 3
    2 * x - y - 6   # 2x - y = 6
]

# 結果格納
results = []

# 各等式制約について解析
for idx, constraint in enumerate(constraints, start=1):
    L = f - λ * constraint  # ラグランジュ関数
    grad_L = [sp.diff(L, var) for var in (x, y, λ)]
    sols = sp.solve(grad_L, (x, y, λ), dict=True)
    
    print(f"\n--- Constraint {idx}: {sp.simplify(constraint)} = 0 ---")
    for sol in sols:
        val = f.subs(sol)
        results.append((sol[x], sol[y], val))
        print(f"x = {sp.simplify(sol[x])}, y = {sp.simplify(sol[y])}, Value = {sp.simplify(val)}")

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?