```python
import numpy as np
import matplotlib.pyplot as plt
import sympy as sy
import math
```

Finding $f(x)=e^{-x}$ using:

a. Compound Simpson's Rule

b. Compound Trapezoidal Rule


```python
#Defining f(x)
def integ(arr):
    integ=0
    analytical=[]
    for num in arr:
        integ+=-sy.exp(-num)
        analytical.append(integ)
    return analytical

def func(arr):
    return sy.exp(-arr)
```


```python
#Defining the array and other related variables
x=10.0
nx=21
xarr=np.linspace(0,x,nx)
print(xarr,dx)
```

    [ 0.   0.5  1.   1.5  2.   2.5  3.   3.5  4.   4.5  5.   5.5  6.   6.5
      7.   7.5  8.   8.5  9.   9.5 10. ] 0.05



```python
#Finding the analytical solution
ex=symbols('x')
print(integrate(func(ex),ex))
integrate(func(ex), (ex,0,10))
```

    -exp(-x)





$\displaystyle 1 - e^{-10}$




```python
#Compound Trapezoidal Rule
integral=0
trapint=[]
for i in range(nx-1):
    integral = 0.5*(xarr[i+1]-xarr[i])*(func(xarr[i]) + func(xarr[i+1]))
    trapint.append(integral)
print(integral)
print(trapint)
```

    3.00629399125464e-5
    [0.401632664928158, 0.243602525221019, 0.147752400329968, 0.0896163608462606, 0.0543550704651279, 0.0329680167479407, 0.0199961129475456, 0.0121282555777632, 0.00735615885674412, 0.00446173588433194, 0.00270617960938738, 0.00164138090378261, 0.000995547842410983, 0.000603830289633022, 0.000366241583925587, 0.000222136749512586, 0.000134732749228289, 8.17195432743309e-5, 4.95654084935950e-5, 3.00629399125464e-5]



```python
#Compound Simpson's Rule
integral=0
simpint=[]
for i in range(0,nx-1,2):
    integral = 1.0/3.0*(xarr[1]-xarr[0])*(func(xarr[i]) + 4*func(xarr[i+1]) + func(xarr[i+2]))
    print(integral)
    simpint.append(integral)
    #simpint.append(1.0/3.0*(xarr[1]-xarr[0])*(func(xarr[i]) + 4*func(xarr[i+1]) + func(xarr[i+2])))
print(integral)
print(simpint)
```

    0.632333680003663
    0.232622560833629
    0.0855770576833453
    0.0314820401576454
    0.0115815953401315
    0.00426063082160135
    0.00156739848568853
    0.000576613679008060
    0.000212124318005295
    7.80361755666611e-5
    7.80361755666611e-5
    [0.632333680003663, 0.232622560833629, 0.0855770576833453, 0.0314820401576454, 0.0115815953401315, 0.00426063082160135, 0.00156739848568853, 0.000576613679008060, 0.000212124318005295, 7.80361755666611e-5]



```python
#Plotting the values
print(integ(xarr))
plt.plot(xarr,-np.exp(-xarr))
plt.plot(xarr[1:],trapint)
plt.plot(xarr[:-1:2], simpint)
```


```python

```

ab620dca1b1c4c0381cb06e77cd4e887d0698f86
ipynb
Jupyter Notebook
Differentiation & Integration/Compound Integration.ipynb
drkndl/PHY-604
2947785b3487a03b88f97ce3cba2a49c4e3b228c
MIT
Differentiation & Integration/Compound Integration.ipynb
drkndl/PHY-604
2947785b3487a03b88f97ce3cba2a49c4e3b228c
MIT
Differentiation & Integration/Compound Integration.ipynb
drkndl/PHY-604
2947785b3487a03b88f97ce3cba2a49c4e3b228c
MIT
Qwen/Qwen-72B
1. YES
2. YES