## 2019年11月29日金曜日

### 数学 - Python - 微分積分学 - 平均値の定理 - 最小値を取る場合、量の測定、最確値

1. $\begin{array}{l}f\left(x\right)=\sum _{i=1}^{n}{\left(x-{a}_{i}\right)}^{2}\\ f\text{'}\left(x\right)=\sum _{i=1}^{n}2\left(x-{a}_{i}\right)\\ =2nx-2\sum _{i=1}^{n}{a}_{i}\\ f\text{'}\left(x\right)=0\\ x=\frac{\sum _{i=1}^{n}{a}_{i}}{n}\end{array}$

コード

#!/usr/bin/env python3
from sympy import pprint, symbols, plot, summation, Derivative, solve
import random

print('11.')

ns = range(1, 11)
x = symbols('x', real=True)
f = sum([(x - symbols(f'a{i}')) ** 2 for i in ns])
d = Derivative(f, x, 1)
for o in [d, d.doit(), solve(d.doit(), x)]:
pprint(o)
print()

n = 10
gs = []
ys = []
for _ in range(5):
bs = [random.randrange(-5, 5) for _ in range(n)]
g = sum([(x - b) ** 2 for b in bs])
gs.append(g)
ys.append(g.subs({x: sum(bs) / n}))

p = plot(*gs, *ys,
ylim=(min(ys) - 5, max(ys) + 5),
legend=False,
show=False)

colors = ['red', 'green', 'blue', 'brown', 'orange',
'purple', 'pink', 'gray', 'skyblue', 'yellow']

for o, color in zip(p, colors):
o.line_color = color

p.show()
p.save('sample11.png')


% ./sample11.py
11.
∂ ⎛         2             2            2            2            2
──⎝(-a₁ + x)  + (-a₁₀ + x)  + (-a₂ + x)  + (-a₃ + x)  + (-a₄ + x)  + (-a₅ + x)
∂x

2            2            2            2            2⎞
+ (-a₆ + x)  + (-a₇ + x)  + (-a₈ + x)  + (-a₉ + x) ⎠

-2⋅a₁ - 2⋅a₁₀ - 2⋅a₂ - 2⋅a₃ - 2⋅a₄ - 2⋅a₅ - 2⋅a₆ - 2⋅a₇ - 2⋅a₈ - 2⋅a₉ + 20⋅x

⎡a₁   a₁₀   a₂   a₃   a₄   a₅   a₆   a₇   a₈   a₉⎤
⎢── + ─── + ── + ── + ── + ── + ── + ── + ── + ──⎥
⎣10    10   10   10   10   10   10   10   10   10⎦

%