Pythonで高校数学の問題を解く(条件つきの最大値・最小値)

問題
 x + y = 1 のとき  x^2 + y^2 の最小値を求めよ。

 x = \dfrac{1}{2}, y = \dfrac{1}{2} のとき最小値  \dfrac{1}{2}


xを-10から10までの適当に細かい値で試す。

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-10, 10, 10000)
y = 1 - x
z = x**2 + y**2

a = list(zip(x, y, z))
# タプルの3番目の要素(z)の最小値を求める
min_x, min_y, min_z = min(a, key=lambda x:x[2])
print('x =', min_x, 'y =', min_y, '最小値 =', min_z)

plt.plot(x, z)
plt.show()
x = 0.4990499049904997 y = 0.5009500950095003 最小値 = 0.5000018053610542

f:id:collatz:20220209160531p:plain