CoCalc Shared Filesidz.ipynb
Author: Александр Комиссаров
Views : 34
In [14]:
#задание1

In [15]:
N = 15
import numpy as np
import random

In [16]:
li = []
for i in range(N):
li += [random.randint(-9, 9)]
print(li)

[-7, -6, -9, 0, 0, 5, 7, 7, 4, 0, -4, 1, 3, -5, -5]
In [17]:
index = 0
chet = []
for i in range(len(li)):
if li[i]%3 == 0:
index += 1
if li[i]%2 == 0:
chet += [li[i]]
print(chet)

[-6, 0, 0, 4, 0, -4]
In [18]:
index

6
In [19]:
sred = sum(chet)/len(chet);sred

-1.0
In [20]:
[index]+li+[sred]

[6, -7, -6, -9, 0, 0, 5, 7, 7, 4, 0, -4, 1, 3, -5, -5, -1.0]
In [21]:
#задание2

In [22]:
nabor = "ab13cdlj5b3l33j38f8gg9s99g90h20hh9d9s75f7s57f97sf8f8s9779691g788gd8g8df98gdf79gdg4d494d59dud8ggdf9gd0gdg949994999444989489489jv4dfjvfv6l7co29"

In [23]:
chisla = []
num = 0
for i in nabor:
if i.isalpha():
chisla += [num]
num = 0
continue
if i.isdigit():
num += 1


In [24]:
print(chisla)

[0, 0, 2, 0, 0, 0, 1, 1, 2, 2, 1, 0, 1, 2, 2, 2, 0, 1, 1, 2, 1, 2, 2, 0, 1, 1, 7, 3, 0, 1, 1, 0, 2, 0, 0, 2, 0, 0, 1, 3, 2, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 21, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0]
In [25]:
max(chisla)

21
In [26]:
#задание3

In [27]:
			N = 5
M = 5
n = 1
mat = np.reshape([1 for x in range(N) for x in range(M)],(N,M));mat
l = np.array([0,0,0,0,0])
L = np.reshape(l,(5,1));print(mat, '\n', L)

[[1 1 1 1 1] [1 1 1 1 1] [1 1 1 1 1] [1 1 1 1 1] [1 1 1 1 1]] [[0] [0] [0] [0] [0]]
In [28]:
new = np.hstack((mat, L));new

array([[1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 0]])
In [29]:
nn = new.transpose();nn

array([[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [0, 0, 0, 0, 0]])
In [30]:
nn[n] =  nn[len(nn) - 1]; nn[len(nn) - 1] = nn[0]

In [31]:
nn

array([[1, 1, 1, 1, 1], [0, 0, 0, 0, 0], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]])
In [32]:
nn.transpose()

array([[1, 0, 1, 1, 1, 1], [1, 0, 1, 1, 1, 1], [1, 0, 1, 1, 1, 1], [1, 0, 1, 1, 1, 1], [1, 0, 1, 1, 1, 1]])
In [33]:
#задание4

In [34]:
A = np.reshape([np.random.randint(2,6) for x in range(60)],(4,15));A = np.array(A);A

array([[3, 4, 5, 3, 2, 3, 2, 3, 4, 2, 5, 4, 4, 5, 5], [3, 3, 5, 2, 2, 5, 3, 4, 3, 2, 2, 2, 5, 4, 4], [5, 2, 5, 5, 5, 2, 4, 5, 2, 4, 3, 2, 5, 3, 3], [4, 3, 4, 3, 2, 5, 3, 3, 3, 4, 5, 5, 2, 3, 5]])
In [35]:
n = []
m = []
for i in range(len(A)):
n = []
for x in A[i]:
if x == 3:
n += [x]
m +=[ n]

In [36]:
print(m)

[[3, 3, 3, 3], [3, 3, 3, 3], [3, 3, 3], [3, 3, 3, 3, 3, 3]]
In [37]:
n = []
m = []
for i in range(len(A)):
n = []
for x in A[i]:
if x == 3:
n += [x]
m +=[ len(n)]

In [38]:
m

[4, 4, 3, 6]
In [39]:
en = list(enumerate(m));en

[(0, 4), (1, 4), (2, 3), (3, 6)]
In [40]:
min(m)

3
In [41]:
di = dict(en);di

{0: 4, 1: 4, 2: 3, 3: 6}
In [42]:
di[2]

3
In [43]:
 res = {v: k for k, v in di.items()}

In [44]:
res

{3: 2, 4: 1, 6: 3}
In [45]:
res[min(m)]

2
In [46]:
k = []
l = []
for i in range(len(A)):
k = []
for j in range(len(A[i])):
if A[i][j] == 3:
k += [j]
l +=[ k]

In [47]:
A[i]

array([4, 3, 4, 3, 2, 5, 3, 3, 3, 4, 5, 5, 2, 3, 5])
In [48]:
l

[[0, 3, 5, 7], [0, 1, 6, 8], [10, 13, 14], [1, 3, 6, 7, 8, 13]]
In [49]:
lo = list(map(lambda x:len(x),l));lo

[4, 4, 3, 6]
In [50]:
minm = lo[0]
pos = 0
for i in range(len(lo)):
print("min=", minm, "pos=", pos)

min= 4 pos= 0 min= 4 pos= 0 min= 4 pos= 0 min= 4 pos= 0

#3адание 5

In [51]:
import matplotlib.pyplot as pl
%matplotlib inline

In [52]:
func = lambda x:  (1-x)/x-3*np.cos(4*x)

In [53]:
x = np.linspace(0, 5, 100)
pl.plot(x,func(x))
pl.annotate('root', xy=(1.15, 0), xytext=(1.4, 4), arrowprops=dict(facecolor='black', shrink=0.05),)
pl.grid(1)
pl.show()

/usr/local/lib/python3.5/dist-packages/ipykernel/__main__.py:1: RuntimeWarning: divide by zero encountered in true_divide if __name__ == '__main__':
In [54]:
import time
t1 = time.clock()
def search(f, stP, finP):
mP=average(stP, finP)
if nearcl(stP, finP):
return mP
test = f(mP)
if test>0:
return search(f, stP, mP)
elif test < 0:
return search(f, mP, finP)
return mP

In [55]:
def average(x, y):
return (x+y)/2

def nearcl(x, y):
if abs(x-y)<0.00001:
return 1
return 0

In [56]:
def halfInterval(f, a ,b):
aVal=f(a)
bVal=f(b)
if aVal>0 and bVal<0:
return search(f, b, a)
elif aVal<0 and bVal>0:
return search(f, a, b)
else:
return 0
t2 = time.clock()
print(t2-t1)

0.025542000000000176
In [ ]:


In [57]:
halfInterval(func, 1, 2) ###########################5

1.1662178039550781
In [ ]:


In [58]:
func = lambda x:  (1-x)/x-3*np.cos(4*x)# метод хорд

In [59]:
import time
t1 = time.clock()
def chord(sp, fp, ep):
while(abs(fp - sp) > ep):
sp = fp - (fp - sp)*func(fp)/(func(fp) - func(sp))
fp = sp + (sp - fp)*func(sp)/(func(sp) - func(fp))
return fp
t2 = time.clock()
print(t2-t1)

0.00014199999999986446
In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [60]:
chord(1, 2, 0.000001)########################

2.0054727407943655
In [61]:
func = lambda x: np.tan(2.5*x)-5*x    #касательных
dif = lambda x: 2.5/np.cos(2.5*x)**2-5

In [62]:
def kas(x0, func, dif, e):
while 1:
x1 = x0 - (func(x0) / dif(x0))
if abs(x1 - x0) < e:
return x1
x0 = x1

In [63]:
kas(0.4, func, dif, 0.0001)#######################

0.4662244740831599
In [64]:
func = lambda x: np.tan(2.5*x)-5*x #простой итерации
dif = lambda x: 2.5/np.cos(2.5*x)**2-5

In [65]:
def iter(sp, fp, ep):
fp = sp - func(sp)/dif(sp)
while(abs(fp - sp) > ep):
sp = fp - func(fp)/dif(fp)
fp = sp - func(sp)/dif(sp)
return fp

In [66]:
iter(0.45,0.5,0.001)##################

0.4662244941232622

# задание 6

In [67]:
import numpy as np
import numpy.linalg as li

In [68]:
A = [[10,2,6], [1,10,9], [2,-7,-10]];A
b = np.array([2.8,7,-17]);b

array([ 2.8, 7. , -17. ])
In [69]:
C = np.reshape([-A[i][j]/A[i][i] for i in range(len(A[0])) for j in range(len(A))],(3,3)) + np.eye(3);print(C)
d = [b[i]/A[i][i] for i in range(len(b))];d

[[ 0. -0.2 -0.6] [-0.1 0. -0.9] [ 0.2 -0.7 0. ]]
[0.27999999999999997, 0.7, 1.7]
In [70]:
li.solve(A,b) #решили для проверки

array([-0.95882353, -1.51764706, 2.57058824])
In [71]:
def lighiter(q1, q2, q3, m=0, ep=0.001): #простой итерации
ind = 0
q = np.array([q1,q2,q3])
x = C.dot(q) + d
while(abs(x[0] - q[0]) > ep and abs(x[1] - q[1]) > ep and abs(x[2] - q[2]) > ep ):
q = C.dot(x) + d
x = C.dot(q) + d
m = m + 1
ind += 1
return (x, ind)
print (m)

In [72]:
q = li.solve(A,b)
x = C.dot(q) + d;x

array([-0.95882353, -1.51764706, 2.57058824])
In [73]:
lighiter(0, 0, 0, 0.0001) ###########################

(array([-0.95822136, -1.51662799, 2.57032029]), 12)
In [74]:
def zeid(q1, q2, q3, ep=0.001): #метод Зейделя
ind = 0
q = np.array([q1,q2,q3])
x1 = C[0][0]*q1 + C[0][1]*q2 + C[0][2]*q3 + d[0]
x2 = C[1][0]*x1 + C[1][1]*q2 + C[1][2]*q3 + d[1]
x3 = C[2][0]*x1 + C[2][1]*x2 + C[2][2]*q3 + d[2]
while(abs(x1 - q1) > ep and abs(x2 - q2) > ep and abs(x3 - q3) > ep):
x1 = C[0][0]*q1 + C[0][1]*q2 + C[0][2]*q3 + d[0]
x2 = C[1][0]*x1 + C[1][1]*q2 + C[1][2]*q3 + d[1]
x3 = C[2][0]*x1 + C[2][1]*x2 + C[2][2]*q3 + d[2]
q1 = C[0][0]*x1 + C[0][1]*x2 + C[0][2]*x3 + d[0]
q2 = C[1][0]*q1 + C[1][1]*x2 + C[1][2]*x3 + d[1]
q3 = C[2][0]*q1 + C[2][1]*q2 + C[2][2]*x3 + d[2]
ind += 1
return [[x1, x2, x3], ind]

In [75]:
zeid(-0.9, -1.5, 2.6, 0.0001) ################################

[[-0.9590177847128027, -1.5182413789451041, 2.570965408319012], 4]
In [76]:
#задание8

In [77]:
fn = lambda x: np.e**(x/3) #аналитически найденные фцнкции
dif = lambda x: (1/3)*np.e**(x/3)
dif2 = lambda x: (1/9)*np.e**(x/3)
a = 0.5; b = 1.5; m = 0.63

In [78]:
rdif = lambda x, d: (fn(x + d) - fn(x))/d
ldif = lambda x, d: (fn(x) - fn(x - d))/d
ddif = lambda x, d: (fn(x - 2*d) - 8*fn(x - d) + 8*fn(x + d) - fn(x + 2*d))/(12*d)
diff = lambda x, d: (fn(x + d) - fn(x - d))/(2*d)

In [79]:
print(dif(m), '=', rdif(m,0.630000001), '=', ldif(m, 0.6300000002), '=', ddif(m, 0.6300000000001), '=', diff(m, 0.63000003))
#аналитическое, #численные

0.41122601998558106 = 0.457592850335902 = 0.3709175554749624 = 0.4111992211183748 = 0.41425520316106124
In [80]:
ddiff = lambda x, d: (fn(x - d) - 2*fn(x) + fn(x + d))/d**2;ddiff(m,0.63)

0.13757983296837314
In [81]:
x = np.linspace(a, b, 50);
xn = np.hstack((x[1:],[10.1]))
f = fn(x); d = dif(x); dd = dif2(x)
dn = rdif(x,xn)
ddn = -ddiff(x,xn)

In [82]:
print(x)

[0.5 0.52040816 0.54081633 0.56122449 0.58163265 0.60204082 0.62244898 0.64285714 0.66326531 0.68367347 0.70408163 0.7244898 0.74489796 0.76530612 0.78571429 0.80612245 0.82653061 0.84693878 0.86734694 0.8877551 0.90816327 0.92857143 0.94897959 0.96938776 0.98979592 1.01020408 1.03061224 1.05102041 1.07142857 1.09183673 1.1122449 1.13265306 1.15306122 1.17346939 1.19387755 1.21428571 1.23469388 1.25510204 1.2755102 1.29591837 1.31632653 1.33673469 1.35714286 1.37755102 1.39795918 1.41836735 1.43877551 1.45918367 1.47959184 1.5 ]
In [83]:
print(xn)

[ 0.52040816 0.54081633 0.56122449 0.58163265 0.60204082 0.62244898 0.64285714 0.66326531 0.68367347 0.70408163 0.7244898 0.74489796 0.76530612 0.78571429 0.80612245 0.82653061 0.84693878 0.86734694 0.8877551 0.90816327 0.92857143 0.94897959 0.96938776 0.98979592 1.01020408 1.03061224 1.05102041 1.07142857 1.09183673 1.1122449 1.13265306 1.15306122 1.17346939 1.19387755 1.21428571 1.23469388 1.25510204 1.2755102 1.29591837 1.31632653 1.33673469 1.35714286 1.37755102 1.39795918 1.41836735 1.43877551 1.45918367 1.47959184 1.5 10.1 ]
In [84]:
import matplotlib.pyplot as plt

In [85]:
plt.figure(figsize=(10,20))
plt.plot(x,f,'ro-',x,d,'r*',x,dd,'gs-',x,d,'y',x,dd, 'b*')
plt.grid(1)
plt.show()

In [86]:
#задание10

In [87]:
fn = lambda x, u: np.cos(u)/(1.25 + x) - 0.3*u**2
lin = np.linspace(0,1,1000)
x0 = 0;u0 = 0;du0 = fn(0,0)
h = 0.001

In [88]:
def eulr(x, u):
y = []
for i in range(len(lin)):
u += h*fn(x, u)
x += h
y += [u]
return y
yu = eulr(0,0)

In [89]:
len(lin), len(yu)

(1000, 1000)
In [90]:
plt.plot(lin,yu)

[<matplotlib.lines.Line2D at 0x7f6d7964d860>]
In [91]:
import numpy as np #проверка
from scipy.integrate import odeint
import matplotlib.pyplot as plt

def fun(y, t, a):
"""Define the right-hand side of equation dy/dt = a*y"""
f = np.cos(y)/(1.25 + t) - 0.3*y**2
return f

# Initial condition
y0 = 0

# Times at which the solution is to be computed.
t = np.linspace(0, 1, 51)

# Parameter value to use in fun.
a = -2.5

# Solve the equation.
y = odeint(fun, y0, t, args=(a,))

# Plot the solution.  odeint is generally used to solve a system
# of equations, so it returns an array with shape (len(t), len(y0)).
# In this case, len(y0) is 1, so y[:,0] gives us the solution.
plt.plot(t, y[:,0])
plt.xlabel('t')
plt.ylabel('y')
plt.show()

In [92]:
##################################################################
fn = lambda x, u: np.cos(u)/(1.25 + x) - 0.3*u**2
lin = np.linspace(0,1,1000)
x0 = 0; u0 = 0; du0 = fn(0,0)
h = 1/len(lin)

In [93]:
def RulkaKutka(f, x0, y0, x1, n):
vx = [0] * (n)
vy = [0] * (n)
h = (x1 - x0) / float(n)
vx[0] = x = x0
vy[0] = y = y0
for i in range(1, n):
k1 = h * f(x, y)
k2 = h * f(x + 0.5 * h, y + 0.5 * k1)
k3 = h * f(x + 0.5 * h, y + 0.5 * k2)
k4 = h * f(x + h, y + k3)
vx[i] = x = x0 + i * h
vy[i] = y = y + (k1 + k2 + k2 + k3 + k3 + k4) / 6
return vy

In [94]:
ty = RulkaKutka(fn,0,0,1,1000)

In [95]:
len(lin), len(ty)

(1000, 1000)
In [96]:
plt.plot(lin,ty)

[<matplotlib.lines.Line2D at 0x7f6d7360aac8>]
In [97]:
plt.plot (lin,yu,'r*',lin,ty, 'y')

[<matplotlib.lines.Line2D at 0x7f6d735e2438>, <matplotlib.lines.Line2D at 0x7f6d735e2710>]
In [98]:
#задание 7

In [99]:
import numpy as np
import matplotlib.pyplot as pl

In [100]:
fn = lambda x: 2*x**2+6 / (x**2-2*x+5)

In [101]:
def fun(x):
return  2*x**2+6 / (x**2-2*x+5)

In [102]:
import numpy as np
import matplotlib.pyplot as plt
n = 5
x = np.linspace(-5, 5, n)
y = fun(x)
def lagranz(x,y,t):
z = 0
for j in range(len(y)):
p1 = 1
p2 = 1
for i in range(len(x)):
if i==j:
p1 = p1*1
p2 = p2*1
else:
p1 *= (t-x[i])
p2 *= (x[j]-x[i])
z += y[j]*p1/p2
return z

In [103]:
xnew=np.linspace(np.min(x),np.max(x),100)
ynew=[lagranz(x,y,i) for i in xnew]
plt.plot(x,y,'o',xnew,ynew)
plt.grid(True)
plt.show()

In [104]:
#################################################################

In [105]:
n = 50
x = np.linspace(-5,5,n)
y = fn(x)

def product( val, n ):
mul = 1
for i in range(n):
if i: mul *= val - x[i-1]
yield mul
C=[]
for n in range(len(x)):
p = product( x[n], n+1 )
C.append( (y[n]-sum(C[k]*next(p) for k in range(n)) )/next(p) )

def f( v ):
return sum(C[k]*p for k, p in enumerate(product(v, len(C)) ))

In [106]:
pl.plot(x, fun(x+0.05), '*', x, f(x))
pl.grid(1)
pl.show()

In [107]:
# задание9

In [108]:
import pandas as pd
import numpy as np
from scipy import optimize, linalg
import scipy
from scipy import spatial
import re
import math
import pandas as pd
from numpy import zeros, dot, savetxt
import matplotlib
from matplotlib import pylab as plt
%matplotlib inline

In [109]:
plt.style.use('ggplot')
print(plt.style.available)

['Solarize_Light2', 'seaborn-paper', 'ggplot', 'fivethirtyeight', '_classic_test', 'dark_background', 'seaborn-poster', 'seaborn-deep', 'fast', 'seaborn-dark-palette', 'seaborn-talk', 'seaborn-darkgrid', 'seaborn', 'tableau-colorblind10', 'seaborn-whitegrid', 'seaborn-bright', 'seaborn-muted', 'seaborn-dark', 'seaborn-white', 'classic', 'grayscale', 'seaborn-colorblind', 'seaborn-ticks', 'bmh', 'seaborn-pastel', 'seaborn-notebook']
In [110]:
def Lin_func(vector):
znach_v = []
for znach in vector:
znach_v += [math.sin(znach / 5) * math.exp(znach / 10) + 5 * math.exp(-znach / 2)]
return znach_v
def EDin_func(znach):
return math.sin(znach / 5) * math.exp(znach / 10) + 5 * math.exp(-znach / 2)

In [111]:
a = np.linspace(1, 15, num = 100)
#a, len(a)
#print Lin_func(a),
b = Lin_func(a)

In [112]:
b = [EDin_func(1.), EDin_func(15.)]
b

[3.252216865271419, 0.6352214195786656]
In [113]:
izn3 = [1., 4., 10., 15.]  #
fzn3 = Lin_func(izn3)

In [114]:
izn3 = [1.2, 1.3, 1.4, 1.6, 1.7, 1.9]
fzn3 = [0.6703, 0.5169, 0.4350, 0.2800, 0.2541, 0.2466]

In [115]:
koeff = []
def koeff_search(izn3 = izn3, fzn3 = fzn3):
work_m = izn3
znach_func = fzn3
for i in range(len(work_m)):            #из списка в матрицу
work_m[i] = [work_m[i]]
for i in range(len(work_m)):            #умножения количества элементов
work_m[i] = work_m[i] * (len(work_m))
N = 0
for i in range(len(work_m)):            #создание матрицы квадратов
for j in range(len(work_m)):
work_m[i][j] = work_m[i][j] ** N
N += 1
N = 0
koeff = np.linalg.solve(work_m, znach_func) #Находим решение системы
print(koeff)
return koeff

In [116]:
def Polin_func1(vector, koeff = koeff):
znach_f = []
for znach in vector:
znach_f += [koeff[0] + ((koeff[1]) * znach) + (koeff[2] * (znach ** 2)) ]
return znach_f

In [117]:
def Polin_func2(vector, koeff = koeff):
znach_v = []
shab = []
for znach in vector:
for i in range(len(koeff)):
shab += [koeff[i] * (znach ** i)]
znach_v += [float(sum(shab))]
shab = []
return znach_v

In [118]:
c =  koeff_search()

[ 409.82909334 -1354.53584685 1787.19101194 -1173.78194447 383.32261906 -49.76587302]
In [119]:
dis = np.linspace(1.2, 1.9, num = 20)
var = Lin_func(dis)
for i in range(len(var)):
var[i] = (var[i])

In [120]:
x = [1.2, 1.3, 1.4, 1.6, 1.7, 1.9]
y = [0.6703, 0.5169, 0.4350, 0.2800, 0.2541, 0.2466]

In [121]:
plt.plot(x, np.array(y), '*', dis, Polin_func2(dis, koeff=c),'-b')
plt.show

<function matplotlib.pyplot.show(*args, **kw)>
In [122]:
print(abs(np.array(y)) - abs(np.array(Polin_func2(x, koeff=c))))
print(np.sqrt(sum([i - sum(y)/len(y) for i in Polin_func2(x, koeff=c)])/(len(x)*(len(x)-1))));print(4.8348823929e-15)
print(y)
print(Polin_func2(x, koeff=c))

[-1.16573418e-14 3.58602037e-14 1.68254299e-13 4.82058837e-13 -3.35065309e-13 2.83412183e-13] 4.8348823929e-15 [0.6703, 0.5169, 0.435, 0.28, 0.2541, 0.2466] [0.6703000000000117, 0.5168999999999642, 0.43499999999983174, 0.27999999999951797, 0.25410000000033506, 0.2465999999997166]
In [ ]:


In [ ]:


In [ ]: