# Integral Exercise # 1


```python
import sympy as sp
x = sp.Symbol('x')
sp.integrate(3.0*x**2 +1, x)
```




    1.0*x**3 + 1.0*x




```python
# Doing numerically
from scipy.integrate import quad
#lets define a function

def f(y):
    return 3.0*y**2 +1
#print(f(2)) -> test it if it work

i = quad(f,0,2)
print(i)
print(i[0])

```

    (10.000000000000002, 1.1102230246251568e-13)
    10.000000000000002



```python
i, error = quad(f, 0, 2)
print(i)
print(error)
```

    10.000000000000002
    1.1102230246251568e-13



```python
# try yourself and plot this with you ipynb
# play around with http://wolframalpha.com, cool site for mathematics
from IPython.display import display, Math, Latex
display(Math(r'f(x) = \int_{0}^{2\pi}e^{-x}{sin(3x)} dx'))
```


$$f(x) = \int_{0}^{2\pi}e^{-x}{sin(3x)} dx$$



```python
#Solution
from scipy.integrate import quad
import numpy as np
# import sympy as sp - this wont really work, you can and should try throwing in numbers to see why its deosn't!

def f(x):
    return np.exp(-x)*np.sin(3.0*x)
i = quad(f, 0, 2*np.pi)
print(i)
```

    (0.29943976718048754, 5.05015300411582e-13)


## Exercise 2:  Simple derivatives or as I'd prefer to call differentials 


```python
# Finding derivative the simple math way

def f(x):
    return x**2

def differential(x):
    h =  1.0/1000.0
    rise = f(x + h) - f(x)
    run = h
    slope = rise / run
    return slope

print(differential(1))
print(differential(2))
print(differential(3))
print(differential(4))
```

    2.0009999999996975
    4.000999999999699
    6.000999999999479
    8.0010000000037



```python
# Integrals are essentially the area under the sinusoidal curve tha covers 
# all reactangular boxes undr the curve covered
def integral(startx, endx, numberofrectangles):
#     width = ((endx) - (startx)) /numberofrectangles = Makes no difference in Py 3.6, with or without float
    width = (float(endx) - float(startx)) /numberofrectangles
    runningSum = 0
    for i in range(numberofrectangles):
        height = f(startx + i*width)
        area = height*width
        runningSum += area
    return runningSum
print('Area is: ', integral(0, 1, 10))
print('Area is: ', integral(0, 1, 1000))
print('Area is: ', integral(0, 1, 100000))
```

    Area is:  0.2850000000000001
    Area is:  0.33283350000000034
    Area is:  0.33332833334999745


## Exercise 3: More integration, interpolation and curve fitting


```python
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from scipy.integrate import *
```

#### You've seen one example of integra before, but lets try another one 

Try solving this: 
$f(x) = \int_{0}^{1}3x^2 + {1} dx$
#### Also BTW just use dollar sign before and after your formula as this $your formula$
to display formulas in your iPython Notebook use the inline function such as 
$$e^x=\sum_{i=0}^\infty \frac{1}{i!}x^i$$


```python
def f(x):
    return 3.0*x**2 + 1.0
xlow = 0
xhigh = 1
i, err = quad(f, xlow, xhigh)
print("Integral is: ", i)
print("Error is :", err)
# Use help(quad) to see what more it can do
```

    Integral is:  2.0
    Error is : 2.220446049250313e-14


#### Let's try interpolation 


```python
from scipy.interpolate import * # We want interpid function
plt.xkcd()

# Here basically you have a series of data points.
# You want to estimate data points that are between given points
# you want to *linearly* interpolate between the given function (meaning drawing a straight line)
# Or, you can use higher order, called polynomial interpolation to approximate the curve between the data points
# Cubic spline is a popular example of this

x_givenpoint = np.linspace(0, 10, 10)
y_givenpoint = np.cos(x_givenpoint**2.0/8.0)



# Now we create an array
xx = np.linspace(0, 10, 1000)
yy = np.cos(xx**2.0/8.0)

plt.plot(x_givenpoint, y_givenpoint, 'x', label = 'given data')
plt.plot(xx, yy, ':', label='Perfect')
plt.ylabel('x')
plt.xlabel('y')
plt.legend(loc='best')

```


```python
x_i = np.linspace(0, 10, 100) #

# do linear interpolation
f_linear = interp1d(x_givenpoint, y_givenpoint)
y_il = f_linear(x_i)

# Cubic spline interpolation

f_spline = interp1d(x_givenpoint, y_givenpoint, kind='cubic')
y_is = f_linear(x_i)

# plot these results
plt.plot(x_givenpoint, y_givenpoint, 'x')
plt.plot(x_i, y_il, 'o')
plt.plot(x_i, y_is, '-')
plt.plot(xx, yy, ':')
plt.legend(['data', 'linear', 'perfect'], loc='best')
```

#### Curve fitting - how does it look like?


```python
x_given = np.array([0., 1., 2., 3., 4., 5.])
y_given = np.array([0, 0.8, 0.9, 0.1, -0.8, -1.0])

x_p = np.linspace(-2.0, 6.0, 100)    # Data for plotting the pply fit
p3 = np.polyfit(x_given, y_given, 3) # 3rd order polynomial object
y_p = np.polyval(p3, x_p)
plt.plot(x_given, y_given, 'o')
plt.plot(x_p, y_p, '-')
plt.legend(['data', 'polyfit'], loc='best')
plt.ylim(-2, 2)
```


```python
print(p3)
```

    [ 0.08703704 -0.81349206  1.69312169 -0.03968254]


#### Lets do some curve fitting
This function is available from scipy.optimizer import * 
Fit function from scipy.org 
$f(x) = a^-bx + c$


```python
from scipy.optimize import *
```


```python
def f(x, a, b, c):
    return a*np.exp(-b*x) + c

# Setting some given data

x_given = np.linspace(0,4,75)
y_given = f(x_given,2.5,1.5,0.8) + 0.2*np.random.normal(size=len(x_given))

# do some curve fitting

params, extras = curve_fit(f, x_given, y_given)

# output / plotting results

print("a=%g, b=%g, c=%g" %(params[0], params[1], params[2]))

plt.plot(x_given, y_given, 'o')
plt.plot(x_given, f(x_given, params[0], params[1], params[2]))
plt.legend(['data', 'curve-fit'], loc='best')
```

# Some more simple calculus stuff
Go to https://sympy.org for more basics


```python
from sympy import *
init_printing() # prints cool output
```


```python
x, y, z = symbols('x,y,z')
my_ex = x*cos(x)
my_ex
```


```python
# substituting this function
my_ex.subs(x, 1)
```


```python
diff(cos(x), x) #diff is the derivative function in sympy
```


```python
diff(exp(x**2), x)
```


```python
diff(x**4, x, x, x) #can take multiple derivatives at once
diff(x**4, x, 3)
```

#### Below will compute the following

$\frac{\partial 7}{\partial x \partial y^2 \partial z^4}e^{xyz}$


```python
expr = exp(x*y*z)
diff(expr, x,y,y,z,z,z,z)
```


```python
diff(expr, x,y,y,z,4)
```


```python
diff(expr, x,y,2,z,4)
```


```python
# It can be called as a method
expr.diff(x,y,y,z,4)
```


```python
# Create unevaluated rerivative by using Derivative class
deriv = Derivative(expr, x,y,y,z,4)
deriv
```


```python
type(Derivative)
```




    sympy.core.assumptions.ManagedProperties




```python
# Evaluate an unevaluated derivaive using doit method
deriv.doit()
```

## A bit more basics of Integrals 

$f(x) = \int_{0}^{∞}e^{-x} dx$

##### alt+5 = infinity symbol



```python
integrate(exp(-x), (x,0, oo))
```

### Integrate this
$\int_{0}^{∞}\int_{-∞}^{∞}e^{-x^2-y^2} dxdy$


```python
integrate(exp(-x**2 - y**2), (x, -oo, oo), (y, -oo, oo))
```


```python
# if integrate isnt able to compute an integral, it returns an unevaluated Integral object
expr = integrate(x**x, x)
print(expr)
```

    Integral(x**x, x)



```python
expr
```


```python
expr = Integral(log(x)**2, x)
expr
```

#### Itegrate uses powerful algorithms including heuristic pattern matching, Risch algorithm and Meijer G-functions
integrate uses powerful algorithms that are always improving to compute both definite and indefinite integrals. Here's a cool example.


```python
integ = Integral((x**4 + x**2*exp(x) - x**2 - 2*x*exp(x) - 2*x - \
                  exp(x))*exp(x)/((x - 1)**2*(x + 1)**2*(exp(x) + 1)), x)
integ
```


```python
integ.doit()
```


```python
integ = Integral(sin(x**2), x)
integ
```


```python
integ.doit()
```


```python
integ = Integral(x**y*exp(-x), (x,0,oo))
integ
```


```python
integ.doit()
```




$$\begin{cases} \Gamma{\left(y + 1 \right)} & \text{for}\: - \Re{\left(y\right)} < 1 \\\int_{0}^{\infty} x^{y} e^{- x}\, dx & \text{otherwise} \end{cases}$$




```python
help(Integral.doit)
```

    Help on function doit in module sympy.integrals.integrals:
    
    doit(self, **hints)
        Perform the integration using any hints given.
        
        Examples
        ========
        
        >>> from sympy import Integral
        >>> from sympy.abc import x, i
        >>> Integral(x**i, (i, 1, 3)).doit()
        Piecewise((2, Eq(log(x), 0)), (x**3/log(x) - x/log(x), True))
        
        See Also
        ========
        
        sympy.integrals.trigonometry.trigintegrate
        sympy.integrals.risch.heurisch
        sympy.integrals.rationaltools.ratint
        as_sum : Approximate the integral using a sum
    


## Coming up Limits... 

$\lim_{a \rightarrow b}{f(x)}$


```python
limit(sin(x)/x, x, 0)
```


```python
expr = x**2/exp(x)
expr.subs(x,oo)
```


```python

```

010198d7340b28ffbd3fb44e7765890606d980bf
ipynb
Jupyter Notebook
python-tuts/intermediate/Calculus with Python.ipynb
DanielMabadeje/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
7adab3877fc1d3f1d5f57e6c1743dae8f76f72c5
Apache-2.0
2020-02-05T18:27:32.000Z
2021-01-05T22:38:50.000Z
python-tuts/intermediate/Calculus with Python.ipynb
nuhaltinsoy/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
6017441f2d476f9c6c568dd886da43c6c0fd89bd
Apache-2.0
2020-01-28T22:22:00.000Z
2022-03-11T23:24:28.000Z
python-tuts/intermediate/Calculus with Python.ipynb
nuhaltinsoy/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
6017441f2d476f9c6c568dd886da43c6c0fd89bd
Apache-2.0
2017-11-28T08:46:31.000Z
2021-02-10T03:34:57.000Z
Qwen/Qwen-72B
1. YES
2. YES