3
1

More than 3 years have passed since last update.

Python numpy で近似式の計算

Last updated at Posted at 2021-07-24
  • 「pythonでサクッと近似式計算できない?Excelだと6次までらしくて...」と相談をいただいたのがきっかけで調べてみました。

結論

numpyのpolynomial(ポリノミアル:多項式)モジュールを使用してn次近似式を算出できる。
(scipyでもできるらしいが比較検証はしてない)

以下のようなコードで近似可能。
コードは上記のように勝手に @wrblue_mica34 様の書かれたpythonで近似式の計算 をベースにさせてもらいました。

ソースコード

main.py
import numpy as np
from matplotlib import pyplot as plt

x= np.linspace(-10,10,20)
#y= x**3 +  2*x**2 + 3*x + 10+ np.random.randn(20)*50
#y= x**11 + x**9 + 1000*x**7 + 6*x**5 + 8*x**3 + x**1 + 10 #+ np.random.randn(20)*50
y = 0.0001*x**10 +0.01*x**7 + 1000*x**3 + 10000*x #+ np.random.randn(20)*1000

#近似式の係数
res1=np.polynomial.Polynomial.fit(x, y, deg=1)
res2=np.polynomial.Polynomial.fit(x, y, deg=2)
res3=np.polynomial.Polynomial.fit(x, y, deg=3)
res4=np.polynomial.Polynomial.fit(x, y, deg=4)
res10=np.polynomial.Polynomial.fit(x, y, deg=10)

print("10次近似式")
print(res10)

#近似式の計算
y1 = res1(x)
y2 = res2(x)
y3 = res3(x)
y4 = res4(x)
y10 = res10(x)

#グラフ表示
plt.scatter(x, y, label='original')
plt.plot(x, y1, label='1deg')
plt.plot(x, y2, label='2deg')
plt.plot(x, y3, label='3deg')
plt.plot(x, y10, label='10deg')
plt.legend()
plt.show()

コマンドライン出力結果

10次近似式
-2.962767826343394e-10 + 99999.99999999747 x**1 +
1.1499998947763862e-08 x**2 + 1000000.0000000066 x**3 -
9.768104439408122e-08 x**4 - 1.380203054314589e-08 x**5 +
2.8865757618439694e-07 x**6 + 100000.00000001301 x**7 -
3.4098936930317207e-07 x**8 - 5.409990936225413e-09 x**9 +
1000000.0000001389 x**10

プロット結果

image.png

参考

3
1
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
3
1