## Mathematics with Python

All notebooks can be found [https://github.com/drvinceknight/mwp](https://github.com/drvinceknight/mwp).

### Requirements for this workshop

- Python (version 3+)
- Sympy
- Numpy
- Matplotlib
- Jupyter notebooks (although if you're comfortable using Python in another way do not feel obliged to use notebooks)

### Arithmetic

It is possible to use Python to carry out arithmetic. For example


```python
2 + 2
```




    4




```python
538 * 612 / 24
```




    13719.0



### Exercises

- Calculate $42 ^ 2$
- Calculate $56 / 2 \times 5$

## Symbolic mathematics

Most of mathematics involves the use of symbolic variables. We can use a python library called `sympy` to do this. For example, let us compute:

$$x + x$$


```python
import sympy as sym
x = sym.Symbol("x")  # Creating a symbolic variable x
x + x
```




    2*x



### Exercises

- Compute $x - 2x$
- Compute $x + 2y - 3x + y$

## Nicer output

`sympy` can use $\LaTeX$ to display mathematics when using Jupyter notebooks:


```python
sym.init_printing()
x + x
```

## Substituting values in to expressions

If we need to compute a numerical value, it is possible to do so:


```python
expr = x + x
expr
```


```python
expr.subs({x: 4})
```

### Exercises

- Substitute $x=5, y=7$ in to the expression: $x + 2y$

## Expanding expressions

We can use `sympy` to verify expressions like the following:

$$(a + b) ^ 2 = a ^ 2 + 2 a b + b ^ 2$$


```python
a, b = sym.symbols("a, b")  # Short hand: note we're using `sym.symbols` and not `sym.Symbol`
expr = (a + b) ** 2
expr
```


```python
expr.expand()
```

A `sympy` expression not only retains mathematical information but also the form, indeed the following two expressions are not the same. They have equal values.


```python
expr == expr.expand()
```




    False



### Exercises

- Expand $(a + b + c)^2$
- Expand $(a + b) ^ 3$

## Factorising expressions

We can also factor expressions like:

$$a ^ 2 - b ^ 2 = (a - b)(a + b)$$


```python
sym.factor(a ** 2 - b ** 2)
```

### Exercises

- Factorise $a ^ 3 - b ^ 3$
- Factorise $4x + x ^ 2 - yx$

## Solving equations

We can use `sympy` to solve algebraic equations. Let us take a look at the quadratic equation:

$$ax^2 + b x + c = 0$$


```python
c = sym.Symbol('c')
eqn = a * x ** 2 + b * x + c 
sym.solveset(eqn, x)
```

### Exercises:

- Obtain the solution to: $ax^3+bx^2+cx+d=0$
- Obtain the solution to $x^2 + 1 = 0$

52ae9f955f0ecea150c6ff8a4b964132321a8236
ipynb
Jupyter Notebook
nbs/01-introduction-and-installation.ipynb
drvinceknight/mwp
51bb5aa699788445f1dd710ee4c7535121f1d60d
MIT
nbs/01-introduction-and-installation.ipynb
drvinceknight/mwp
51bb5aa699788445f1dd710ee4c7535121f1d60d
MIT
2018-02-17T16:36:11.000Z
2018-02-19T15:01:53.000Z
nbs/01-introduction-and-installation.ipynb
drvinceknight/mwp
51bb5aa699788445f1dd710ee4c7535121f1d60d
MIT
2018-02-19T13:48:25.000Z
2022-03-29T10:42:08.000Z
Qwen/Qwen-72B
1. YES
2. YES