<jupyter_start><jupyter_text>Interpolación de Lagrange<jupyter_code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from IPython.display import Image<jupyter_output><empty_output><jupyter_text>1. Ejemplo 3 puntos<jupyter_code>#Hacemos la interpolación con tres puntos de la tabla
#(205,1724.3);(210,1907.7);(215,2105.9)
X=np.array([205,210,215])
Y=np.array([1724.3,1907.7,2105.9])

datos=pd.read_csv("vapor_Saturado.csv",delimiter=",")
print(datos)
X=datos['T(°C)']<jupyter_output>T(°C)  P_sat(kPa)  v_f(m^3/kg)  v_g(m^3/kg)
0    205      1724.3     0.000116      0.11508
1    210      1907.7     0.001173      0.10429
2    215      2105.9     0.001180      0.09468<jupyter_text>Formula para los coeficientes de interpolación:x: Punto a interpolar ; n: número de puntos-1    $$ L_{i}(x)=\Pi_{j=0,j\neq i}^{n}\frac{(x-x_{j})}{(x_{i}-x_{j})} $$ $ i=0,...,n$$$ p(x)=\sum_{i=0}^{n}y_{i}*L_{i}(x)$$<jupyter_code>#Coeficientes de p(x
#x: punto a interpolar
#X: datos en x, Y datos en y
def L0(x,X):#i=0, j=1,2
    return (x-X[1])*(x-X[2])/((X[0]-X[1])*(X[0]-X[2]))
def L1(x,X):#i=1,j=0,2
    return (x-X[0])*(x-X[2])/((X[1]-X[0])*(X[1]-X[2]))
def L2(x,X):#i=1,j=0,1
    return (x-X[0])*(x-X[1])/((X[2]-X[0])*(X[2]-X[1]))
#sumatoria para el polinomio
def p_lagrange(x,X,Y):
    return L0(x,X)*Y[0]+L1(x,X)*Y[1]+L2(x,X)*Y[2]
x=207.5#K; valor a interpolar
p_lagrange(x,X,Y)
import sympy as sy
x=sy.symbols('x')
L0(x,X)
print(L1(x,X))
print(L2(x,X))
print(p_lagrange(x,X,Y))
sy.expand(p_lagrange(x,X,Y))<jupyter_output><empty_output><jupyter_text>2. Interpolación de P vs T  y generalización programa Lagrange<jupyter_code>#base del polinomio L_i
def L(i,x,X,n):#i=0, j=1,2
    prod=1
    for j in range(n):
        if(i!=j):
            prod*=(x-X[j])/(X[i]-X[j])
    return prod
#Calculo de los polinomios haciendo una sumatoria de los productos L_iy_i
def p_lagrange(x,X,Y):
    n=len(X)
    suma=0
    for i in range(n):
#         print(type(L(i,x,X,n)))
#         print(type(Y[i]))
        suma+=L(i,x,X,n)*Y[i]
    return suma<jupyter_output><empty_output><jupyter_text>DatosTomados de la tabla A-5 del Cengel para las propiedades del agua saturada, obtenidos mediante cálculoscon la formulación de la IAPWS para las propiedades del agua.https://doi.org/10.1063/1.1461829 \http://www.iapws.org/newform.html<jupyter_code>datos=pd.read_csv("thermodynamical_tables_water.csv",delimiter="\t",header=[0,1,2])
datos<jupyter_output><empty_output><jupyter_text>Opcional: Modificamos los indices para que queden los multiíndices de forma adecuada<jupyter_code>a=[x[j] for x in datos.columns for j in range(3)]
a=np.reshape(a,[int(len(a)/3),3])
a[3][0]=a[2][0]
a[5][0]=a[4][0]
a[6][0]=a[4][0]
a[8][0]=a[7][0]
a[9][0]=a[7][0]
a[11][0]=a[10][0]
a[12][0]=a[10][0]
a=[tuple(a[i]) for i in range(len(a))]
col_names =pd.MultiIndex.from_tuples(a)
datos.columns=col_names
datos
T=datos["Temp. (°C)"]["Temp."]["T"]
P=datos["Sat. press. (kPa)"]["Sat. press."]["Psat"]
v_f=datos['Specific volume  (m3/kg)']['Sat. liquid.']['v_f']
v_g=datos['Specific volume  (m3/kg)']['Sat.vapor.']['v_g']
s_f=datos['Entropy  (kJ/kg·K)']['Sat. liquid.']['s_f']
s_fg=datos['Entropy  (kJ/kg·K)']['Evap.']['s_fg']
s_g=datos['Entropy  (kJ/kg·K)']['Sat.vapor.']['s_g']
T_inter=np.linspace(7.5,372.5,74)<jupyter_output><empty_output><jupyter_text>Tabla interpolación P vs T<jupyter_code>P_pred_complete=p_lagrange(T_inter,T,P)#[p_lagrange(t,T,P) for t in T_inter]
results_complete=pd.DataFrame({"T(°C)":T_inter,"P predicted (kPa)":P_pred_complete})
P_pred_pag914=p_lagrange(T_inter[40:],np.array(T[40:]),np.array(P[40:]))#[p_lagrange(t,T,P) for t in T_inter]
# P_pred_pag914=p_lagrange(T_inter[50:-20],np.array(T[50:-20]),np.array(P[50:-20]))
# results_pag914=pd.DataFrame({"T(°C)":T_inter[40:],"P predicted (kPa)":P_pred_pag914})
print(results_complete)<jupyter_output>T(°C)  P predicted (kPa)
0     7.5      -5.813055e+15
1    12.5       2.033932e+14
2    17.5      -1.010549e+13
3    22.5       6.550517e+11
4    27.5      -5.267777e+10
..    ...                ...
69  352.5      -6.488619e+11
70  357.5       9.860509e+12
71  362.5      -1.932409e+14
72  367.5       5.182995e+15
73  372.5      -1.688322e+17

[74 rows x 2 columns]<jupyter_text>5. a) Gráfica<jupyter_code>plt.figure()
plt.plot(T_inter[12:-13],P_pred_complete[12:-13])
plt.scatter(T,P)
plt.xlabel('T(°C)')
plt.ylabel('P(kPa)')
plt.savefig("P_vs_T_completo.png")
plt.figure()
plt.plot(T_inter[41:-2],P_pred_pag914[1:-2])
plt.xlabel('T(°C)')
plt.ylabel('P(kPa)')
# plt.plot(T_inter[50:-20],P_pred_pag914[:])
plt.scatter(T[40:],P[40:])
plt.savefig("P_vs_T_pag_914.png")<jupyter_output><empty_output><jupyter_text>3. Tabla interpolación $v_f$ vs T<jupyter_code>v_f_pred_complete=p_lagrange(T_inter,T,v_f)#[p_lagrange(t,T,P) for t in T_inter]
results_complete=pd.DataFrame({"T(°C)":T_inter,"v_f predicted (m^3/kg)":v_f_pred_complete})
v_f_pred_pag914=p_lagrange(T_inter[40:],np.array(T[40:]),np.array(v_f[40:]))#[p_lagrange(t,T,P) for t in T_inter]
# results_pag914=pd.DataFrame({"T(°C)":T_inter[40:],"P predicted (kPa)":P_pred_pag914})
print(results_complete)<jupyter_output>T(°C)  v_f predicted (m^3/kg)
0     7.5            5.462886e+09
1    12.5           -1.866936e+08
2    17.5            9.045329e+06
3    22.5           -5.707461e+05
4    27.5            4.459041e+04
..    ...                     ...
69  352.5            2.138649e+06
70  357.5           -3.202643e+07
71  362.5            6.189650e+08
72  367.5           -1.638380e+10
73  372.5            5.270369e+11

[74 rows x 2 columns]<jupyter_text>5. b) Gráfica<jupyter_code>plt.figure()
plt.plot(T_inter[13:-15],v_f_pred_complete[13:-15])
plt.scatter(T,v_f)
plt.savefig("v_f_vs_T_completo.png")
plt.xlabel('T(°C)')
plt.ylabel('v_f(m^3/kg)')
plt.figure()
plt.plot(T_inter[42:-3],v_f_pred_pag914[2:-3])
plt.scatter(T[40:],v_f[40:])
plt.xlabel('T(°C)')
plt.ylabel('v_f(m^3/kg)')
plt.savefig("v_f_vs_T_pag_914.png")<jupyter_output><empty_output><jupyter_text>4. Tabla interpolación $v_g$ vs T<jupyter_code>v_g_pred_complete=p_lagrange(T_inter,T,v_g)#[p_lagrange(t,T,P) for t in T_inter]
results_complete=pd.DataFrame({"T(°C)":T_inter,"v_g predicted (m^3/kg)":v_g_pred_complete})
v_g_pred_pag914=p_lagrange(T_inter[40:],np.array(T[40:]),np.array(v_g[40:]))#[p_lagrange(t,T,P) for t in T_inter]
# results_pag914=pd.DataFrame({"T(°C)":T_inter[40:],"P predicted (kPa)":P_pred_pag914})
print(results_complete)<jupyter_output>T(°C)  v_g predicted (m^3/kg)
0     7.5           -3.061732e+11
1    12.5            1.071279e+10
2    17.5           -5.322977e+08
3    22.5            3.450948e+07
4    27.5           -2.775827e+06
..    ...                     ...
69  352.5           -3.610596e+07
70  357.5            5.480133e+08
71  362.5           -1.072732e+10
72  367.5            2.874121e+11
73  372.5           -9.352780e+12

[74 rows x 2 columns]<jupyter_text>5. c) Gráfica<jupyter_code>plt.figure()
plt.plot(T_inter[13:-13],v_g_pred_complete[13:-13])
plt.scatter(T,v_g)
plt.xlabel('T(°C)')
plt.ylabel('v_g(m^3/kg)')
plt.savefig("v_g_vs_T_completo.png")
plt.figure()
plt.plot(T_inter[41:-2],v_g_pred_pag914[1:-2])
plt.scatter(T[40:],v_g[40:])
plt.xlabel('T(°C)')
plt.ylabel('v_g(m^3/kg)')
plt.savefig("v_g_vs_T_pag_914.png")<jupyter_output><empty_output><jupyter_text>Laboratorio métodos  3. Tabla interpolación $s_f$ vs T<jupyter_code>s_f_pred_complete=p_lagrange(T_inter,T,s_f)#[p_lagrange(t,T,P) for t in T_inter
results_complete=pd.DataFrame({"T(°C)":T_inter,"s_f predicted (m^3/kg)":s_f_pred_complete})
print(results_complete)<jupyter_output>T(°C)  s_f predicted (m^3/kg)
0     7.5            5.202882e+12
1    12.5           -1.823609e+11
2    17.5            9.076901e+09
3    22.5           -5.894807e+08
4    27.5            4.749684e+07
..    ...                     ...
69  352.5            4.737520e+08
70  357.5           -7.232524e+09
71  362.5            1.423440e+11
72  367.5           -3.833041e+12
73  372.5            1.253216e+14

[74 rows x 2 columns]<jupyter_text>5. b) Gráfica<jupyter_code>plt.figure()
plt.plot(T_inter[13:-14],s_f_pred_complete[13:-14])
plt.scatter(T,s_f)
plt.xlabel('T(°C)')
plt.ylabel('s_f(kJ/(kg.K))')
plt.savefig("s_f_vs_T_completo.png")
s_fg_pred_complete=p_lagrange(T_inter,T,s_fg)#[p_lagrange(t,T,P) for t in T_inter

results_complete=pd.DataFrame({"T(°C)":T_inter,"s_fg predicted (m^3/kg)":s_fg_pred_complete})
print(results_complete)
plt.figure()
plt.plot(T_inter[13:-14],s_fg_pred_complete[13:-14])
plt.scatter(T,s_fg)
plt.xlabel('T(°C)')
plt.ylabel('s_fg(kJ/(kg.K))')
plt.savefig("s_fg_vs_T_completo.png")<jupyter_output>T(°C)  s_fg predicted (m^3/kg)
0     7.5            -2.913548e+12
1    12.5             1.016829e+11
2    17.5            -5.038514e+09
3    22.5             3.256779e+08
4    27.5            -2.611181e+07
..    ...                      ...
69  352.5            -4.036504e+08
70  357.5             6.108892e+09
71  362.5            -1.192592e+11
72  367.5             3.187217e+12
73  372.5            -1.034717e+14

[74 rows x 2 columns]<jupyter_text>4. Tabla interpolación $s_g$ vs T<jupyter_code>s_g_pred_complete=p_lagrange(T_inter,T,s_g)#[p_lagrange(t,T,P) for t in T_inter]
results_complete=pd.DataFrame({"T(°C)":T_inter,"s_g predicted (m^3/kg)":s_g_pred_complete})

print(results_complete)<jupyter_output>T(°C)  s_g predicted (m^3/kg)
0     7.5           -6.050236e+12
1    12.5            2.125737e+11
2    17.5           -1.060843e+10
3    22.5            6.909016e+08
4    27.5           -5.584118e+07
..    ...                     ...
69  352.5           -5.085413e+08
70  357.5            7.763265e+09
71  362.5           -1.527888e+11
72  367.5            4.114423e+12
73  372.5           -1.345295e+14

[74 rows x 2 columns]<jupyter_text>5. c) Gráfica<jupyter_code>plt.figure()
plt.plot(T_inter[12:-13],s_g_pred_complete[12:-13])
plt.scatter(T,s_g)
plt.xlabel('T(°C)')
plt.ylabel('s_f(kJ/(kg.K))')
plt.savefig("s_g_vs_T_completo.png")<jupyter_output><empty_output><jupyter_text>6 a) Resultados y análisis Observamos en prácticamente todas las gráficas que los polinomios de interpolación de Lagrange muestran resultados similares a los valores proporcionados en el apéndice, sin embargo en los puntos extremos el polinomio de Lagrange tiene a diverger oscilatoriamente. Este fenómeno se conoce como el fenómeno de Runge, el cual ocurre porque aunque exista un polinomio de interpolación a la función verdadera. no se conoce si el polinomio de Lagrange se acercará a dicho polinomio. Además, al tener un número considerable de datos n=76, el polinomio interpolado va a tener una derivada de alto orden que va a ir aumentando si aumentamos el número de puntos y nos alejamos del origen, con lo cual las oscilaciones van a aumentar a medida que nos alejamos de los datos.<jupyter_code>plt.figure()
plt.plot(s_f_pred_complete[15:-16],T_inter[15:-16],c='r',label="Interpolación s_f")
plt.scatter(s_f,T,c='tab:blue',label='Datos')
plt.plot(s_g_pred_complete[15:-16],T_inter[15:-16],c='g',label="Interpolación s_g")
plt.scatter(s_g,T,c='tab:blue')
plt.ylabel('T (°C)')
plt.xlabel('s (kJ/(kg.K))')
plt.legend()
plt.savefig("diagrama_TS_completo.png")
Image(url= "TS_diagram_cengel.png", width=600, height=600)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1821826280623608, 'fraction_numerical': 0.11581291759465479, 'mean_word_length': 3.9129102844638948, 'pattern_counts': {'":': 18, '<': 62, '<?xml version=': 0, '>': 62, 'https://': 1, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '17', 'dir': 'jupyter-structured-clean-dedup', 'id': '497235', 'license': 'MIT', 'n_tokens_mistral': 5901, 'n_tokens_neox': 5248, 'n_words': 784, 'path': 'Act_4_lagrange/.ipynb_checkpoints/interpolacion-checkpoint.ipynb', 'repo_name': 'jerck1/MetodosComputacionales1', 'size': '11225'}