# A first example how to use Function_from_Expression

Determine the equation of a linear function 

$$
  f(x) = a\,x + b
$$ 

where the points $P(2|3)$ and $Q(-2,5)$ belong to the graph 

$$
  y=f(x)
$$ 

of $f$ and plot the graph $y=f(x)$ for $-4\le x\le 4$.

## Solution

To solve this, we first need some initialisations:


```python
from sympy import *
init_printing()

import matplotlib.pyplot as plt

# usually you want this
%matplotlib inline 

# useful for OS X
%config InlineBackend.figure_format='retina' 

import numpy as np

from IPython.display import display, Math

from fun_expr import Function_from_Expression as FE
```

In the next step, the function $f$ is defined with two unknown coefficients $a$, $b$:


```python
# define the function

# the variable of the function
x = Symbol('x')

# the unknown coefficients:
a,b = symbols('a,b')

# the function
f = FE(x, a*x+b)

# display result
f
```


```python
# or, better
Math("f(x)="+latex(f(x)))
```




$$f(x)=a x + b$$



The unknown coefficients $a$, $b$ need to be determined. To do this, a system of linear equations is derived from the given points:


```python
# define points:
x_p,y_p = 2,3
x_q,y_q = -2,5

pts = [(x_p,y_p),(x_q,y_q)]

# define equations
eqns = [Eq(f(x_p),y_p),
        Eq(f(x_q),y_q)]

# display result
for eq in eqns:
    display(eq)
```

The resulting system of equations is solved:


```python
# solve equations
sol = solve(eqns)

# display result
sol
```

The solution is substituted into the function.


```python
# substitute results into f
f = f.subs(sol)

# display result
Math("f(x)="+latex(f(x)))
```




$$f(x)=- \frac{x}{2} + 4$$



The resulting function is plotted over the interval $-4\le x \le 4$


```python
# define new plot
fig, ax = plt.subplots()

# the interval along the x-axis
lx = np.linspace(-4,4)

# plot f(x)
ax.plot(lx,f.lambdified(lx),label=r"$y={f}$".format(f=latex(f(x))))

# insert the given points to the graph
ax.scatter(*zip(*pts))

# some additional commands
ax.grid(True)
ax.axhline(0,c='k')
ax.axvline(0,c='k')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.legend(loc='upper right')
```

bff83f08fbae96d845a7f1f0209edd9841dbe31d
ipynb
Jupyter Notebook
docs/02-first_example.ipynb
w-meiners/fun-expr
a44f0366f08c8c2d2eb2702176698bfe3f6febed
MIT
2017-12-20T16:16:40.000Z
2022-02-28T11:06:38.000Z
docs/02-first_example.ipynb
w-meiners/fun-expr
a44f0366f08c8c2d2eb2702176698bfe3f6febed
MIT
docs/02-first_example.ipynb
w-meiners/fun-expr
a44f0366f08c8c2d2eb2702176698bfe3f6febed
MIT
2020-01-27T09:50:59.000Z
2020-01-27T09:50:59.000Z
Qwen/Qwen-72B
1. YES
2. YES