You are on page 1of 23

yum

October 26, 2016


In [51]: from sympy import *
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
init_printing(use_latex=True)

0.1

Yuber Alejandro Galeano Traslavia 2168292

0.1.1

Polinomios Chevichev segunda clase

0.1.2

Usando las relaciones de recurrencia Pn+1 = 2x Pn (x) Pn1 (x). Se tomarn los
polinmios P0 (x) = 1 y P1 (x) = 2x

1.1

Interpolacin
In [131]: def Chevi2(n):
x = symbols("x")
P1 = 1
P2 = 2*x
if n==0:
return 1
else:
if n<0:
return "n debe ser mayor o igual a cero"
else:
if n==1:
P=P1
else:
if n==2:
P=P2
else:
for i in range (2,n):
P= 2*x*P2-P1
P2=P
P1=P2
return P
1

1.0.1

Definir Polinomio

In [53]: P=Chevi2(4)
expand(P)
Out[53]:
8x3 4x2 2x + 1
1.0.2

Evaluar polinomio 11 puntos

1.2

Interpolacin
In [54]: x = symbols("x")
X=np.linspace(-1,1,11)
Y=np.linspace(-1,1,11)
for i in range (0,len(X)):
Y[i]=P.subs({x:X[i]})
fig, ax = plt.subplots()
ax.plot(X, Y, 'b', label='P', linewidth=1.0)
legend = ax.legend(loc=1, shadow=True,fontsize=9)
ax.set_xlabel('x')
ax.set_ylabel('y')
Out[54]: <matplotlib.text.Text at 0x7fd82d543a90>

In [55]: def evalf(a,b,n,P):


Xex=np.linspace(a,b,n)
Yex=np.linspace(a,b,n)
for i in range (0,len(Xex)):
Yex[i]=P.subs({x:Xex[i]})
return Xex,Yex
Xex,Yex=evalf(-1,1,500,P)

1.3

Interpolacin

3.1
3.1.1

INTERPOLACIN
LAGRANGE

In [56]: L = symbols("L")
x = symbols("x")
L=0;
for i in range (0,len(X)):
k=1
for j in range(0,len(X)):
if i!=j:
k=k*((x-X[j])/(X[i]-X[j]))
L=L+Y[i]*k
3.1.2

LINEAL SEGMENTARIA

In [57]: M=[]
for i in range(0,len(X)-1):
M.append(0)
In [58]: for i in range (0,len(M)):
M[i] = Y[i]+((Y[i+1]-Y[i])/(X[i+1]-X[i]))*(x-X[i])
In [59]: M
Out[59]:

[24.72x + 15.72,

15.44x + 8.296,

8.08x + 3.88,

2.64x + 1.704,

0.880000000000001x + 1.0,

2.48x + 1.0,

3.1.3

CUADRATICA SEGMENTARIA

In [60]: c=[]
for i in range(0,len(X)-2):
c.append(0)

In [61]: for i in range (0,len(c)):


h=X[i+1]-X[i]
c[i] = Y[i]+((Y[i+1]-Y[i])/h)*(x-X[i])+((Y[i+2]-2*Y[i+1]+Y[i])/(h**2))
for i in range (0,len(c)):
c[i]=expand(c[i])
In [62]: c
Out[62]:

46.4x2 58.8x 21.4,

36.8x2 36.08x 9.36799999999999,

27.2x2 19.12x 2.648,

1.4

Interpolacin
4.0.1

Prueba Lagrange 200 puntos

In [63]: Y1=np.linspace(-1,1,200)
X1=np.linspace(-1,1,200)
for i in range (0,len(X1)):
Y1[i]=L.subs({x:X1[i]})
fig, ax = plt.subplots()
ax.plot(X1, Y1, 'b:', label='P lagrange', linewidth=1.0)
ax.plot(Xex, Yex, 'g', label='P exact', linewidth=1.0)
legend = ax.legend(loc=1, shadow=True,fontsize=9)
ax.set_xlabel('x')
ax.set_ylabel('y')
Out[63]: <matplotlib.text.Text at 0x7fd825bb5908>

17.6x2 7.92x

4.0.2

Prueba Lineal segmentaria 200 puntos

In [64]: num=2000
X2=np.linspace(-1,1,num)
Y2=np.zeros(len(X2))
a=int(np.round(num/len(M)))
for i in range (0,len(M)):
for j in range (0,a):
Y2[i*a+j]=M[i].subs({x:X2[i*a+j]})
fig, ax = plt.subplots()
ax.plot(X2, Y2, 'b', label='Spline Lineal', linewidth=1.0)
ax.plot(Xex, Yex, 'g', label='P exact', linewidth=1.0)
legend = ax.legend(loc=1, shadow=True,fontsize=9)
ax.set_xlabel('x')
ax.set_ylabel('y')
Out[64]: <matplotlib.text.Text at 0x7fd82620b1d0>

4.0.3

Prueba cuadratica segmentaria 200 puntos

In [65]: num=2000
X3=np.linspace(-1,1,num)
Y3=np.zeros(len(X3))
a=int(np.round(num/(len(c)+1)))
for i in range (0,len(c)):
for j in range (0,a):
if i==len(c)-1:
Y3[i*a+j]=c[i].subs({x:X3[i*a+j]})
Y3[i*a+j+a]=c[i].subs({x:X3[i*a+j+a]})
else:
Y3[i*a+j]=c[i].subs({x:X3[i*a+j]})
fig, ax = plt.subplots()
ax.plot(X3, Y3, 'b', label='Spline Cuadrtica', linewidth=1.0)
ax.plot(X, Y, 'bo', label='Spline Cuadrtica', linewidth=1.0)
ax.plot(Xex, Yex, 'g', label='P exact', linewidth=1.0)
legend = ax.legend(loc=1, shadow=True,fontsize=9)
ax.set_xlabel('x')
ax.set_ylabel('y')
Out[65]: <matplotlib.text.Text at 0x7fd825b7a898>
6

1.5

Interpolacin
5.0.1

Agregar valores aleatorios

In [66]: x = symbols("x")
X=np.linspace(-1,1,11)
Y=np.linspace(-1,1,11)
error=np.linspace(-1,1,11)
for i in range (0,len(X)):
Y[i]=P.subs({x:X[i]})
e=np.max(np.abs(Y))/5
for i in range (0,len(X)):
error[i]=e*(np.random.rand(1)[0]-0.5)
Yerror=np.linspace(-1,1,11)
Yerror=Y+error
fig, ax = plt.subplots()
ax.plot(X, Yerror, 'bo', label='P + error', linewidth=1.3)

ax.plot(Xex, Yex, 'r', label='P exact')


legend = ax.legend(loc=1, shadow=True,fontsize=9)
ax.set_xlabel('x')
ax.set_ylabel('y')
Out[66]: <matplotlib.text.Text at 0x7fd826082588>

5.0.2

Prueba Lagrange

In [67]: Le = symbols("Le")
x = symbols("x")
Le=0;
for i in range (0,len(X)):
k=1
for j in range(0,len(X)):
if i!=j:
k=k*((x-X[j])/(X[i]-X[j]))
Le=Le+Yerror[i]*k
Y1=np.linspace(-1,1,200)
X1=np.linspace(-1,1,200)
for i in range (0,len(X1)):
Y1[i]=Le.subs({x:X1[i]})

fig, ax = plt.subplots()
ax.plot(X, Yerror, 'bo', label='P + error', linewidth=1.3)
ax.plot(X1, Y1, 'b', label='Aprox', linewidth=1.0)
ax.plot(Xex, Yex, 'g', label='P exact', linewidth=1.0)
legend = ax.legend(loc='best', shadow=True,fontsize=9)
ax.set_xlabel('x')
ax.set_ylabel('y')
Out[67]: <matplotlib.text.Text at 0x7fd8260715f8>

5.0.3

Prueba Lineal segmentaria

In [68]: Me=[]
for i in range(0,len(X)-1):
Me.append(0)
for i in range (0,len(Me)):
Me[i] = Yerror[i]+((Yerror[i+1]-Yerror[i])/(X[i+1]-X[i]))*(x-X[i])
num=2000
X2=np.linspace(-1,1,num)
Y2=np.zeros(len(X2))
a=int(np.round(num/len(Me)))

for i in range (0,len(Me)):


for j in range (0,a):
Y2[i*a+j]=Me[i].subs({x:X2[i*a+j]})
fig, ax = plt.subplots()
ax.plot(X, Yerror, 'bo', label='P + error', linewidth=1.3)
ax.plot(X2, Y2, 'b', label='Aprox', linewidth=1.0)
ax.plot(Xex, Yex, 'g', label='P exact', linewidth=1.0)
legend = ax.legend(loc='best', shadow=True,fontsize=9)
ax.set_xlabel('x')
ax.set_ylabel('y')
Out[68]: <matplotlib.text.Text at 0x7fd825e46550>

5.0.4

Prueba Lineal cuadrtica

In [180]: ce=[]
for i in range(0,len(X)-2):
ce.append(0)

for i in range (0,len(ce)):


h=X[i+1]-X[i]
ce[i] = Yerror[i]+((Yerror[i+1]-Yerror[i])/h)*(x-X[i])+((Yerror[i+2]-

10

num=200
X10=np.linspace(-1,1,num)
Y10=np.zeros(len(X10))
a=int(np.round(num/(len(ce)+1)))
for i in range (0,len(ce)):
for j in range (0,a):
if i==len(c)-1:
Y10[i*a+j]=c[i].subs({x:X10[i*a+j]})
Y10[i*a+j+a]=c[i].subs({x:X10[i*a+j+a]})
else:
Y10[i*a+j]=ce[i].subs({x:X10[i*a+j]})
fig, ax = plt.subplots()
ax.plot(X, Yerror, 'bo', label='P + error', linewidth=1.3)
ax.plot(X10, Y10, 'b', label='Aprox', linewidth=1.0)
ax.plot(Xex, Yex, 'g', label='P exact', linewidth=1.0)
legend = ax.legend(loc='best', shadow=True,fontsize=9)
ax.set_xlabel('x')
ax.set_ylabel('y')
Out[180]: <matplotlib.text.Text at 0x7fd825db7780>

11

1.6

Interpolacin
6.0.1

INTERPOLACIN CON LIBRERAS DE PYTHON

6.0.2

1-D interpolation (interp1d)

The interp1d class in scipy.interpolate is a convenient method to create a function based on fixed
data points which can be evaluated anywhere within the domain defined by the given data using
linear interpolation.
In [70]: from scipy.interpolate import interp1d
x1 = X
y = Yerror
f = interp1d(x1, y)
f2 = interp1d(x1, y, kind='cubic')

xnew = np.linspace(-1, 1, num=41, endpoint=True)


plt.plot(Xex,Yex,'b:',x1, y, 'o', xnew, f(xnew), '-', xnew, f2(xnew), '--'
plt.legend(['real','data', 'linear', 'quadratic'], loc='best')
plt.show()

12

6.1

INTEGRACIN
(m)

Dentro del intervalo de definicion de su polinomio calcule los valores de los integrales In =
Rb
a W (x)Pn (x)Pn+1 (x)dx, para n = 1 a 5, m =0 a 5 usando cuadraturas de Trapecios, de Simpson y
de Gauss con seleccion de paso de integracion automtico en la base del algoritmo de Runge.

1.1

Integracin
7.0.1

PARA ESTE CASO REALIC EL CLCULO CON N=2 y M=3

(para todas las dems convinaciones se realiza de la misma forma)


7.0.2

TRAPECIOS

7.0.3

Funcin

In [91]: def trapecios(a,b,n,Px):


x = symbols("x")
X3=np.linspace(a,b,n+1)
Y3=np.linspace(a,b,n+1)
for i in range (0,len(X3)):
Y3[i]=Px.subs({x:X3[i]})
I=0
I1=0
for i in range(len(X3)):
n=len(X3)
if (i==0)or(i==len(X3)-1):
I=I+Y3[i]/2
else:
I=I+Y3[i]
I1=((b-a)/(n-1))*I
return I1,X3,Y3
In [181]: N=2
M=3
Px1=Chevi2(N)
Px2=Chevi2(M)
W=(1-x**2)**0.5
Px=Px1*Px2*W
Xex2,Yex2=evalf(-1,1,500,Px)
I1,X3,Y3=trapecios(-1,1,8,Px)
fig, ax = plt.subplots()

13

ax.plot(X3, Y3, 'bo')


ax.plot(X3, Y3, 'b', label='Aprox', linewidth=1.0)
ax.plot(Xex2, Yex2, 'g:', label='P exact', linewidth=1.0)
legend = ax.legend(loc=1, shadow=True,fontsize=9)
ax.set_xlabel('x')
ax.set_ylabel('y')
I1
Out[181]:
0.0

7.1
7.1.1

SIMPSON
Funcin Simpson

In [142]: def simpson38(a,b,n,Px):


x = symbols("x")
X3=np.linspace(a,b,n+1)
Y3=np.linspace(a,b,n+1)
for i in range (0,len(X3)):
Y3[i]=Px.subs({x:X3[i]})
I=0
I1=0
14

for i in range(len(X3)):
n=len(X3)
if (i==0)or(i==len(X3)-1):
I=I+Y3[i]
else:
if ((i+2)%3==0)or((i+1)%3==0):
I=I+3*Y3[i]
else:
I=I+2*Y3[i]
I1=(3/8)*((b-a)/(n-1))*I
return I1,X3,Y3
In [143]: Ix,X5,Y5=simpson38(-1,1,200,Px)
Ix
Out[143]:
0.00108820176413
7.1.2

CUADRATURA GAUSS

1.2

Integracin
8.0.1

INTEGRACIN CON LIBRERAS DE PYTHON

The scipy.integrate sub-package provides several integration techniques including an ordinary


differential equation integrator. An overview of the module is provided by the help command:
8.0.2

Trapecios

In [144]: X7,Y7=evalf(-1,1,11,Px)
import scipy.integrate as integrate
integrate.trapz(Y7,X7)
Out[144]:
5.55111512313e 17
8.0.3

Simpson

In [145]: integrate.simps(Y7,X7)
Out[145]:
0.0
15

8.0.4

Gauss

In [149]: init_printing(use_latex=True)
expand(Px)
Out[149]:
8x3 x2 + 1

0.5

2x x2 + 1

0.5

In [150]: result = integrate.quad(lambda x: 8*x**3*(-x**2+1)**0.5-2*x*(-x**2+1)**0.


result[0]
Out[150]:
0.0

1.3

Integracin
Se comprob que al utilizar los algoritmos propios o las libreras correspondientes de python
para esos mismos mtodos los resultados obtenidos son similares con un error menor al 1%

9.1

SOLUCIN DE ECUACIONES TRASCENCENTES

10

1.1

Solucin de ecuaciones transcendentes


In [275]: # algoritmo de separacin de ceros de su polinomio
def ceros(a,b,n,P):
r=[]
X=np.linspace(a,b,n)
h=X[1]-X[0]
for i in X:
if i != b:
if P.subs({x:i})*P.subs({x:i+h})<0:
r.append(i)
m=len(r)
return r,m
In [250]: ceros(-100,100,1000,Chevi2(6))
Out[250]:
([0.5005005005] ,

11

1.2

Solucin de ecuaciones transcendentes


16

1)

11.0.1

PARA ESTE CASO REALIC EL CLCULO CON N=3

(para todas las dems convinaciones se realiza de la misma forma)


11.0.2

Mtodo de biseccin

In [191]: n=3
P=Chevi2(n+1)
In [185]: def bis(a,b,P):
i=0
while i == 0:
c=(a+b)/2
m=P.subs({x:c})
if abs(m)<0.00001:
r=c
i=1
else:
if (P.subs({x:c}))*(P.subs({x:a}))<0:
b=c
else:
a=c
return r

In [192]: x = symbols("x")
a=-1
b=0
Xex5,Yex5=evalf(a,b,500,P)
fig, ax = plt.subplots()
ax.plot(bis(a,b,P),P.subs({x:bis(a,b,P)}), 'bo',label='raz', linewidth=1
ax.plot(Xex5, Yex5, 'g:', label='P exact', linewidth=1.0)
legend = ax.legend(loc=1, shadow=True,fontsize=9)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.grid(True)
bis(-1,0,P)
Out[192]:
0.5

17

11.0.3

Mtodo de Newton-Raphson

In [222]: def newton(P,x0):


i=0
a=0
r=x0
while i == 0:
f=P/diff(P)
m=P.subs({x:r})
if np.abs(m)<0.00001:
i=1
else:
r=r-float(f.subs({x:r}))
a=a+1
#print(a)
if a>500:
i=1
return float(r)
In [227]: pnt=10
r=newton(P,pnt)
a=r-1
b=r+1
Xex5,Yex5=evalf(a,b,500,P)
18

fig, ax = plt.subplots()
ax.plot(newton(P,pnt),P.subs({x:newton(P,pnt)}), 'bo',label='raz', linew
ax.plot(Xex5, Yex5, 'g:', label='P exact', linewidth=1.0)
legend = ax.legend(loc=1, shadow=True,fontsize=9)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.grid(True)
r
Out[227]:
0.5009192158879139

12

1.3

Solucin de ecuaciones transcendentes


12.0.1

RACES CON LIBRERAS DE PYTHON

In [219]: expand(P)
Out[219]:
8x3 4x2 2x + 1
19

In [220]: coeff = [8, -4, -2, 1]


np.roots(coeff)
Out[220]: array([-0.5
12.0.2

0.49999999,

0.50000001])

Races para diferentes Pn (x)

Asegrese que las races del polinomio Pn (x) se ubican entre las races del polinomio Pn+1 (x) y
las races del polinomio Pn+1 (x) se ubican entre las races del polinomio Pn+2 (x)
12.0.3

Para P5 (x)

In [251]: expand(Chevi2(5))
Out[251]:
16x4 16x3 + 4x 1
In [264]: #programa propio
ceros(-10,10,1000,Chevi2(5))
Out[264]:
([0.510510510511,

0.49049049049] ,

2)

In [253]: #Con la librera numpy de python


np.roots([16, -16, 0, 4, -1])
Out[253]: array([-0.50000000 +0.00000000e+00j,
0.50000212 -3.67585920e-06j,
12.0.4

0.50000212 +3.67585920e-06j,
0.49999576 +0.00000000e+00j])

Para P6 (x)

In [254]: expand(Chevi2(6))
Out[254]:
32x5 48x4 + 16x3 + 8x2 6x + 1
In [265]: #programa propio
ceros(-10,10,1000,Chevi2(6))
Out[265]:
([0.510510510511] ,

1)

In [267]: #Con la librera numpy de python


np.roots([32, -48, 16, 8, -6, 1])
Out[267]: array([-0.50000000 +0.00000000e+00j, 0.50004902 +4.90270499e-05j,
0.50004902 -4.90270499e-05j, 0.49995098 +4.90142493e-05j,
0.49995098 -4.90142493e-05j])
20

12.0.5

Para P7 (x)

In [256]: expand(Chevi2(7))
Out[256]:
64x6 128x5 + 80x4 20x2 + 8x 1
In [266]: #programa propio
ceros(-10,10,1000,Chevi2(7))
Out[266]:
([0.510510510511,

0.49049049049] ,

2)

In [268]: #Con la librera numpy de python


np.roots([64, -128, 80, 0, -20, 8, -1])
Out[268]: array([-0.50000000+0.j
,
0.50025458-0.00018523j,
0.49990251-0.00029893j,
12.0.6

0.50025458+0.00018523j,
0.49990251+0.00029893j,
0.49968583+0.j
])

Para P10 (x)

In [259]: expand(Chevi2(10))
Out[259]:
512x9 1792x8 + 2560x7 1792x6 + 448x5 + 224x4 224x3 + 80x2 14x + 1
In [269]: #programa propio
ceros(-10,10,1000,Chevi2(10))
Out[269]:
([0.510510510511] ,

1)

In [260]: #Con la librera numpy de python


np.roots([512, -1792, 2560, -1792, 448, 224, -224, 80, -14, 1])
Out[260]: array([-0.50000000+0.j
,
0.50431021+0.00423207j,
0.50007155+0.00609521j,
0.49569025+0.00437563j,

21

0.50601453+0.j
,
0.50431021-0.00423207j,
0.50007155-0.00609521j,
0.49569025-0.00437563j,

0.49384145+0.j

12.0.7

Para P11 (x)

In [261]: expand(Chevi2(11))
Out[261]:
1024x10 4096x9 + 6912x8 6144x7 + 2688x6 672x4 + 384x3 108x2 + 16x 1
In [270]: #programa propio
ceros(-10,10,1000,Chevi2(11))
Out[270]:
([0.510510510511,

0.49049049049] ,

2)

In [262]: #Con la librera numpy de python


np.roots([1024, -4096, 6912, -6144, 2688, 0, -672, 384, -108, 16, -1])
Out[262]: array([-0.50000000+0.j
,
0.50846515-0.00295909j,
0.50481232-0.00774775j,
0.49869975-0.00926231j,
0.49282637-0.00628835j,
12.0.8

0.50846515+0.00295909j,
0.50481232+0.00774775j,
0.49869975+0.00926231j,
0.49282637+0.00628835j,
0.49039283+0.j
])

Para P12 (x)

In [272]: expand(Chevi2(12))
Out[272]:
2048x11 9216x10 +17920x9 19200x8 +11520x7 2688x6 1344x5 +1440x4 600x3 +140x2 18x+1
In [273]: #programa propio
ceros(-10,10,1000,Chevi2(12))
Out[273]:
([0.510510510511] ,

1)

In [274]: #Con la librera numpy de python


np.roots([2048, -9216, 17920, -19200, 11520, -2688, -1344, 1440, -600, 14
Out[274]: array([-0.50000000+0.j
,
0.52187862-0.00727659j,
0.51310613-0.01874054j,
0.49950072-0.02256568j,
0.48658484-0.01779069j,
0.47892969-0.00668902j])
22

0.52187862+0.00727659j,
0.51310613+0.01874054j,
0.49950072+0.02256568j,
0.48658484+0.01779069j,
0.47892969+0.00668902j,

13

1.4

Se observa que todos los polinomios tienen las mismas races reales, los polinomios impares tienen
2 races reales y los pares una sola, los programas propios predicen las misma races pero nicamente las reales, con una precicin aceptable.

23

You might also like