In [1]:
from math import sin, exp
In [2]:
def func(x):
return sin(x / 5.) * exp(x / 10.) + 5. * exp(-x / 2.)
In [3]:
import numpy as np
from scipy import linalg
In [4]:
arrCoordinates = np.arange(1., 15.1, 0.1)
arrFunction = np.array([func(coordinate) for coordinate in arrCoordinates])
In [5]:
#многочлен первой степени
arrCoord1 = np.array([1, 15])
N = 2
arrA1 = np.empty((0, N))
for i in xrange(N):
arrA1Line = list()
for j in xrange(N):
arrA1Line.append(arrCoord1[i] ** j)
arrA1 = np.append(arrA1, np.array([arrA1Line]), axis = 0)
arrB1 = np.array([func(coordinate) for coordinate in arrCoord1])
print arrCoord1
print arrA1
print arrB1
In [6]:
arrX1 = linalg.solve(arrA1, arrB1)
print arrX1
In [7]:
def func1(x): return arrX1[0] + arrX1[1] * x
arrFunc1 = np.array([func1(coordinate) for coordinate in arrCoordinates])
In [2]:
%matplotlib inline
import matplotlib.pylab as plt
In [3]:
plt.plot(arrCoordinates, arrFunction, arrCoordinates, arrFunc1)
plt.show()
In [10]:
#многочлен второй степени
arrCoord2 = np.array([1, 8, 15])
N = 3
arrA2 = np.empty((0, N))
for i in xrange(N):
arrA2Line = list()
for j in xrange(N):
arrA2Line.append(arrCoord2[i] ** j)
arrA2 = np.append(arrA2, np.array([arrA2Line]), axis = 0)
arrB2 = np.array([func(coordinate) for coordinate in arrCoord2])
print arrCoord2
print arrA2
print arrB2
In [11]:
arrX2 = linalg.solve(arrA2, arrB2)
print arrX2
In [12]:
def func2(x): return arrX2[0] + arrX2[1] * x + arrX2[2] * (x ** 2)
arrFunc2 = np.array([func2(coordinate) for coordinate in arrCoordinates])
In [13]:
plt.plot(arrCoordinates, arrFunction, arrCoordinates, arrFunc1, arrCoordinates, arrFunc2)
plt.show()
In [14]:
#многочлен третьей степени
arrCoord3 = np.array([1, 4, 10, 15])
N = 4
arrA3 = np.empty((0, N))
for i in xrange(N):
arrA3Line = list()
for j in xrange(N):
arrA3Line.append(arrCoord3[i] ** j)
arrA3 = np.append(arrA3, np.array([arrA3Line]), axis = 0)
arrB3 = np.array([func(coordinate) for coordinate in arrCoord3])
print arrCoord3
print arrA3
print arrB3
In [15]:
arrX3 = linalg.solve(arrA3, arrB3)
print arrX3
In [16]:
def func3(x): return arrX3[0] + arrX3[1] * x + arrX3[2] * (x ** 2) + arrX3[3] * (x ** 3)
arrFunc3 = np.array([func3(coordinate) for coordinate in arrCoordinates])
In [17]:
plt.plot(arrCoordinates, arrFunction, arrCoordinates, arrFunc1, arrCoordinates, arrFunc2, arrCoordinates, arrFunc3)
plt.show()
In [18]:
with open('answer2.txt', 'w') as fileAnswer:
for item in arrX3:
fileAnswer.write(str(item) + ' ')
In [ ]: