パイソンで多項式

  • np.poly():根を与えると、それを根とする多項式の係数が返る。複素根もOK。多項式係数と、変数値を与えて多項式関数値を返すのが、np.polyval()
a = [-1,1]

out =np.poly([-1,1])

out[0]*a[0]**2 + out[1]*a[0]**1 + out[2]*a[0]**0 # np.polyval(out,a[0])
Out[185]: 0

np.polyval(out,a[1])
Out[186]: 0

a = [-1,pi]

out =np.poly(a)

np.polyval(out,a[0])
Out[189]: 0.0

np.polyval(out,a[1])
Out[190]: 0.0

out
Out[191]: array([ 1.        , -2.14159265, -3.14159265])
a = [1+2j,3+3j,pi]

out = np.poly(a)

out
Out[195]: 
array([ 1.00000000 +0.j        , -7.14159265 -5.j        ,
        9.56637061+24.70796327j,  9.42477796-28.27433388j])

np.polyval(out,a[0])
Out[196]: (-3.5527136788005009e-15+3.5527136788005009e-15j)
  • 逆に、多項式係数を与えて、根を求めるには、np.roots()
np.roots(out)
Out[197]: array([ 3.14159265+0.j,  3.00000000+3.j,  1.00000000+2.j])
d = np.polyder([1,1,1,1])

d
Out[200]: array([3, 2, 1])

np.polyint(d)
Out[201]: array([ 1.,  1.,  1.,  0.])

x = np.random.uniform(0,1,1000)
a = [3,4,2]
y = np.polyval(a,x)
y_ = y + np.random.randn(len(x))*0.1
out = np.polyfit(x,y_,2)
import pylab as pl
pl.scatter(x,y_)
a
Out[275]: [3, 4, 2]

out
Out[276]: array([ 2.92626667,  4.06572077,  1.99380093])