# <center> Interpolación de Lagrange <center>


```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from IPython.display import Image
```

## 1. Ejemplo 3 puntos


```python
#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])

```


```python
datos=pd.read_csv("vapor_Saturado.csv",delimiter=",")
print(datos)
X=datos['T(°C)']
```

       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


## 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)$$ 


```python
#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]))
```


```python
#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]
```


```python
x=207.5#K; valor a interpolar
p_lagrange(x,X,Y)
```




    1814.1499999999999




```python
import sympy as sy
```


```python
x=sy.symbols('x')
```


```python
L0(x,X)
```




$\displaystyle \frac{\left(x - 215\right) \left(x - 210\right)}{50}$




```python
print(L1(x,X))
```

    -(x - 215)*(x - 205)/25



```python
print(L2(x,X))
```

    (x - 210)*(x - 205)/50



```python
print(p_lagrange(x,X,Y))
```

    34.486*(x - 215)*(x - 210) - 76.308*(x - 215)*(x - 205) + 42.118*(x - 210)*(x - 205)



```python
sy.expand(p_lagrange(x,X,Y))
```




$\displaystyle 0.295999999999992 x^{2} - 86.1599999999962 x + 6947.69999999972$



## 2. Interpolación de P vs T  y generalización programa Lagrange


```python
#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
```

## Datos
Tomados 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


```python
datos=pd.read_csv("thermodynamical_tables_water.csv",delimiter="\t",header=[0,1,2])
datos
```




<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead tr th {
        text-align: left;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr>
      <th></th>
      <th>Temp. (°C)</th>
      <th>Sat. press. (kPa)</th>
      <th>Specific volume  (m3/kg)</th>
      <th>Unnamed: 3_level_0</th>
      <th>Internal energy  (kJ/kg)</th>
      <th>Unnamed: 5_level_0</th>
      <th>Unnamed: 6_level_0</th>
      <th>Enthalpy  (kJ/kg)</th>
      <th>Unnamed: 8_level_0</th>
      <th>Unnamed: 9_level_0</th>
      <th>Entropy  (kJ/kg·K)</th>
      <th>Unnamed: 11_level_0</th>
      <th>Unnamed: 12_level_0</th>
    </tr>
    <tr>
      <th></th>
      <th>Temp.</th>
      <th>Sat. press.</th>
      <th>Sat. liquid.</th>
      <th>Sat.vapor.</th>
      <th>Sat. liquid.</th>
      <th>Evap.</th>
      <th>Sat.vapor.</th>
      <th>Sat. liquid.</th>
      <th>Evap.</th>
      <th>Sat.vapor.</th>
      <th>Sat. liquid.</th>
      <th>Evap.</th>
      <th>Sat.vapor.</th>
    </tr>
    <tr>
      <th></th>
      <th>T</th>
      <th>Psat</th>
      <th>v_f</th>
      <th>v_g</th>
      <th>u_f</th>
      <th>u_fg</th>
      <th>u_g</th>
      <th>h_f</th>
      <th>h_fg</th>
      <th>h_g</th>
      <th>s_f</th>
      <th>s_fg</th>
      <th>s_g</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>0.01</td>
      <td>0.6117</td>
      <td>0.001000</td>
      <td>206.000000</td>
      <td>0.000</td>
      <td>2374.9</td>
      <td>2374.90</td>
      <td>0.001</td>
      <td>2500.9</td>
      <td>2500.9</td>
      <td>0.0000</td>
      <td>9.1556</td>
      <td>9.1556</td>
    </tr>
    <tr>
      <th>1</th>
      <td>5.00</td>
      <td>0.8725</td>
      <td>0.001000</td>
      <td>147.030000</td>
      <td>21.019</td>
      <td>2360.8</td>
      <td>2381.80</td>
      <td>21.020</td>
      <td>2489.1</td>
      <td>2510.1</td>
      <td>0.0763</td>
      <td>8.9487</td>
      <td>9.0249</td>
    </tr>
    <tr>
      <th>2</th>
      <td>10.00</td>
      <td>1.2281</td>
      <td>0.001000</td>
      <td>106.220000</td>
      <td>42.020</td>
      <td>2346.6</td>
      <td>238.87</td>
      <td>42.022</td>
      <td>2477.2</td>
      <td>2519.2</td>
      <td>0.1511</td>
      <td>8.7488</td>
      <td>8.8999</td>
    </tr>
    <tr>
      <th>3</th>
      <td>15.00</td>
      <td>1.7057</td>
      <td>0.001001</td>
      <td>77.885000</td>
      <td>62.980</td>
      <td>2332.5</td>
      <td>2395.50</td>
      <td>62.982</td>
      <td>2465.4</td>
      <td>2528.3</td>
      <td>0.2245</td>
      <td>8.5559</td>
      <td>8.7803</td>
    </tr>
    <tr>
      <th>4</th>
      <td>20.00</td>
      <td>2.3392</td>
      <td>0.001002</td>
      <td>57.762000</td>
      <td>83.913</td>
      <td>2318.4</td>
      <td>2402.30</td>
      <td>83.915</td>
      <td>2453.5</td>
      <td>2537.4</td>
      <td>0.2965</td>
      <td>8.3696</td>
      <td>8.6661</td>
    </tr>
    <tr>
      <th>...</th>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
    </tr>
    <tr>
      <th>71</th>
      <td>355.00</td>
      <td>17570.0000</td>
      <td>0.001808</td>
      <td>0.007872</td>
      <td>1682.200</td>
      <td>706.4</td>
      <td>2388.60</td>
      <td>1714.000</td>
      <td>812.9</td>
      <td>2526.9</td>
      <td>3.8442</td>
      <td>1.2942</td>
      <td>5.1384</td>
    </tr>
    <tr>
      <th>72</th>
      <td>360.00</td>
      <td>18666.0000</td>
      <td>0.001895</td>
      <td>0.006950</td>
      <td>1726.200</td>
      <td>625.7</td>
      <td>2351.90</td>
      <td>1761.500</td>
      <td>720.1</td>
      <td>2481.6</td>
      <td>3.9165</td>
      <td>1.1373</td>
      <td>5.0537</td>
    </tr>
    <tr>
      <th>73</th>
      <td>365.00</td>
      <td>19822.0000</td>
      <td>0.002015</td>
      <td>0.006009</td>
      <td>1777.200</td>
      <td>526.4</td>
      <td>2303.60</td>
      <td>1817.200</td>
      <td>605.5</td>
      <td>2422.7</td>
      <td>4.0004</td>
      <td>0.9489</td>
      <td>4.9493</td>
    </tr>
    <tr>
      <th>74</th>
      <td>370.00</td>
      <td>21044.0000</td>
      <td>0.002217</td>
      <td>0.004953</td>
      <td>1844.500</td>
      <td>385.6</td>
      <td>2230.10</td>
      <td>1891.200</td>
      <td>443.1</td>
      <td>2334.3</td>
      <td>4.1119</td>
      <td>0.6890</td>
      <td>4.8009</td>
    </tr>
    <tr>
      <th>75</th>
      <td>373.95</td>
      <td>22064.0000</td>
      <td>0.003106</td>
      <td>0.003106</td>
      <td>2015.700</td>
      <td>0.0</td>
      <td>2015.70</td>
      <td>2084.300</td>
      <td>0.0</td>
      <td>2084.3</td>
      <td>4.4070</td>
      <td>0.0000</td>
      <td>4.4070</td>
    </tr>
  </tbody>
</table>
<p>76 rows × 13 columns</p>
</div>



Opcional: Modificamos los indices para que queden los multiíndices de forma adecuada


```python
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
```


```python
datos
```




<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead tr th {
        text-align: left;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr>
      <th></th>
      <th>Temp. (°C)</th>
      <th>Sat. press. (kPa)</th>
      <th colspan="2" halign="left">Specific volume  (m3/kg)</th>
      <th colspan="3" halign="left">Internal energy  (kJ/kg)</th>
      <th colspan="3" halign="left">Enthalpy  (kJ/kg)</th>
      <th colspan="3" halign="left">Entropy  (kJ/kg·K)</th>
    </tr>
    <tr>
      <th></th>
      <th>Temp.</th>
      <th>Sat. press.</th>
      <th>Sat. liquid.</th>
      <th>Sat.vapor.</th>
      <th>Sat. liquid.</th>
      <th>Evap.</th>
      <th>Sat.vapor.</th>
      <th>Sat. liquid.</th>
      <th>Evap.</th>
      <th>Sat.vapor.</th>
      <th>Sat. liquid.</th>
      <th>Evap.</th>
      <th>Sat.vapor.</th>
    </tr>
    <tr>
      <th></th>
      <th>T</th>
      <th>Psat</th>
      <th>v_f</th>
      <th>v_g</th>
      <th>u_f</th>
      <th>u_fg</th>
      <th>u_g</th>
      <th>h_f</th>
      <th>h_fg</th>
      <th>h_g</th>
      <th>s_f</th>
      <th>s_fg</th>
      <th>s_g</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>0.01</td>
      <td>0.6117</td>
      <td>0.001000</td>
      <td>206.000000</td>
      <td>0.000</td>
      <td>2374.9</td>
      <td>2374.90</td>
      <td>0.001</td>
      <td>2500.9</td>
      <td>2500.9</td>
      <td>0.0000</td>
      <td>9.1556</td>
      <td>9.1556</td>
    </tr>
    <tr>
      <th>1</th>
      <td>5.00</td>
      <td>0.8725</td>
      <td>0.001000</td>
      <td>147.030000</td>
      <td>21.019</td>
      <td>2360.8</td>
      <td>2381.80</td>
      <td>21.020</td>
      <td>2489.1</td>
      <td>2510.1</td>
      <td>0.0763</td>
      <td>8.9487</td>
      <td>9.0249</td>
    </tr>
    <tr>
      <th>2</th>
      <td>10.00</td>
      <td>1.2281</td>
      <td>0.001000</td>
      <td>106.220000</td>
      <td>42.020</td>
      <td>2346.6</td>
      <td>238.87</td>
      <td>42.022</td>
      <td>2477.2</td>
      <td>2519.2</td>
      <td>0.1511</td>
      <td>8.7488</td>
      <td>8.8999</td>
    </tr>
    <tr>
      <th>3</th>
      <td>15.00</td>
      <td>1.7057</td>
      <td>0.001001</td>
      <td>77.885000</td>
      <td>62.980</td>
      <td>2332.5</td>
      <td>2395.50</td>
      <td>62.982</td>
      <td>2465.4</td>
      <td>2528.3</td>
      <td>0.2245</td>
      <td>8.5559</td>
      <td>8.7803</td>
    </tr>
    <tr>
      <th>4</th>
      <td>20.00</td>
      <td>2.3392</td>
      <td>0.001002</td>
      <td>57.762000</td>
      <td>83.913</td>
      <td>2318.4</td>
      <td>2402.30</td>
      <td>83.915</td>
      <td>2453.5</td>
      <td>2537.4</td>
      <td>0.2965</td>
      <td>8.3696</td>
      <td>8.6661</td>
    </tr>
    <tr>
      <th>...</th>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
    </tr>
    <tr>
      <th>71</th>
      <td>355.00</td>
      <td>17570.0000</td>
      <td>0.001808</td>
      <td>0.007872</td>
      <td>1682.200</td>
      <td>706.4</td>
      <td>2388.60</td>
      <td>1714.000</td>
      <td>812.9</td>
      <td>2526.9</td>
      <td>3.8442</td>
      <td>1.2942</td>
      <td>5.1384</td>
    </tr>
    <tr>
      <th>72</th>
      <td>360.00</td>
      <td>18666.0000</td>
      <td>0.001895</td>
      <td>0.006950</td>
      <td>1726.200</td>
      <td>625.7</td>
      <td>2351.90</td>
      <td>1761.500</td>
      <td>720.1</td>
      <td>2481.6</td>
      <td>3.9165</td>
      <td>1.1373</td>
      <td>5.0537</td>
    </tr>
    <tr>
      <th>73</th>
      <td>365.00</td>
      <td>19822.0000</td>
      <td>0.002015</td>
      <td>0.006009</td>
      <td>1777.200</td>
      <td>526.4</td>
      <td>2303.60</td>
      <td>1817.200</td>
      <td>605.5</td>
      <td>2422.7</td>
      <td>4.0004</td>
      <td>0.9489</td>
      <td>4.9493</td>
    </tr>
    <tr>
      <th>74</th>
      <td>370.00</td>
      <td>21044.0000</td>
      <td>0.002217</td>
      <td>0.004953</td>
      <td>1844.500</td>
      <td>385.6</td>
      <td>2230.10</td>
      <td>1891.200</td>
      <td>443.1</td>
      <td>2334.3</td>
      <td>4.1119</td>
      <td>0.6890</td>
      <td>4.8009</td>
    </tr>
    <tr>
      <th>75</th>
      <td>373.95</td>
      <td>22064.0000</td>
      <td>0.003106</td>
      <td>0.003106</td>
      <td>2015.700</td>
      <td>0.0</td>
      <td>2015.70</td>
      <td>2084.300</td>
      <td>0.0</td>
      <td>2084.3</td>
      <td>4.4070</td>
      <td>0.0000</td>
      <td>4.4070</td>
    </tr>
  </tbody>
</table>
<p>76 rows × 13 columns</p>
</div>




```python
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)
```

### Tabla interpolación P vs T


```python
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)
```

        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]


### 5. a) Gráfica


```python
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")
```

### 3. Tabla interpolación $v_f$ vs T


```python
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)
```

        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]


### 5. b) Gráfica


```python
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")
```

### 4. Tabla interpolación $v_g$ vs T


```python
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)
```

        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]


### 5. c) Gráfica


```python
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")
```

## Laboratorio métodos

### 3. Tabla interpolación $s_f$ vs T


```python
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)
```

        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]


### 5. b) Gráfica


```python
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")
```


```python
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")
```

### 4. Tabla interpolación $s_g$ vs T


```python
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)
```

        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]


### 5. c) Gráfica


```python
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")
```

## 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.


```python
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")
```


```python
Image(url= "TS_diagram_cengel.png", width=600, height=600)
```








Por otro lado, al considerar el diagrama TS (T vs s_f y T vs s_g) tanto para los datos como para el polinomido de interpolación, vemos que se puede reproducir el diagrama TS para la región del vapor saturado y que corresponde a la curva de color negro en el Cengel p 924. Para las regiones interiores a la curva se debe conocer los porcentajes que hay en la mezcla de f (fluido) con g (gas) de agua. Si miramos la interpolación, vemos que no el polinomio no puede predecir valores de temperatura bajos ni valores cercanos al punto crítico (donde coexisten las fases)

## 6 b) Conclusiones

* Exceptuando los primeros 16 y los últimos 16 datos, el polinomios de interpolación de Lagrange muestran resultados similares a los valores proporcionados en el apéndice.
* En los puntos extremos el polinomio de Lagrange presenta el fenómeno de Runge, observándose oscilaciones.
* El polinomio de Lagrange es útil para una cantidad baja de puntos, como 3 puntos.
* Se puede revisar el error porcentual para conocer el margen de error con respecto a los teóricos y no solo estimar la diferencia en orden de magnitud o gráficamente.
* Se pueden realizar pruebas con diferente cantidad de puntos para conocer cuando es suficientemente buena la interpolación de Lagrange.
* Los puntos de la entropía proporcionan una mejor interpretación de los datos para el análisis del estudiante puesto que existen diagramas TS en la literatura, así como diagramas HS (diagrama de Mollier)
* Para una primera instancia se recomienda realizar análisis con las tablas de gas ideal para estudiantes novicios, para los otros se pueden dejar estos datos y/o analizar las tablas de vapor sobrecalentada (curvas de nivel)


```python

```

3aa57c1e00ffe56a7681aebbb560d74c4779efb9
ipynb
Jupyter Notebook
Act_4_lagrange/.ipynb_checkpoints/interpolacion-checkpoint.ipynb
jerck1/MetodosComputacionales1
a0002ea81902e6649ae05983faf59ac1bcb3f2ed
MIT
2022-03-18T00:17:30.000Z
2022-03-18T00:17:30.000Z
Act_4_lagrange/.ipynb_checkpoints/interpolacion-checkpoint.ipynb
jerck1/MetodosComputacionales1
a0002ea81902e6649ae05983faf59ac1bcb3f2ed
MIT
Act_4_lagrange/.ipynb_checkpoints/interpolacion-checkpoint.ipynb
jerck1/MetodosComputacionales1
a0002ea81902e6649ae05983faf59ac1bcb3f2ed
MIT
2022-03-08T22:11:50.000Z
2022-03-18T00:17:31.000Z
Qwen/Qwen-72B
1. YES
2. YES