```python
from sympy import *
from sympy.physics.hydrogen import R_nl
init_printing()

x = symbols('x')
```

# Code Generation 


```python
expr = R_nl(3, 1, x, 1)
expr
```


```python
from sympy.utilities.autowrap import ufuncify
from sympy.utilities.lambdify import lambdify

fn_numpy   = lambdify(x, expr, 'numpy')
fn_fortran = ufuncify([x], expr)
```

## They work the same


```python
from numpy import linspace
xx = linspace(0, 1, 5)
fn_numpy(xx)
```




    array([ 0.        ,  0.02666343,  0.0469299 ,  0.06182246,  0.07222782])




```python
fn_fortran(xx)
```




    array([ 0.        ,  0.02666343,  0.0469299 ,  0.06182246,  0.07222782])



## Plot form with matplotlib


```python
from matplotlib.pyplot import plot, show, legend
%matplotlib inline
```


```python
xx = linspace(0, 5, 50000)  # More points 
plot(xx, fn_numpy(xx))
```


```python
# Time fn_numpy
%timeit fn_numpy(xx)
```

    1000 loops, best of 3: 841 µs per loop



```python
# Time fn_fortran
%timeit fn_fortran(xx)
```

    1000 loops, best of 3: 654 µs per loop


## More complex problem

Lets compute both the expression and its derivative simultaneously. 



```python
outputs = expr, simplify(expr.diff(x))
outputs
```


```python
fn_numpy  = lambdify([x], outputs, 'numpy')

fns_fortran = [ufuncify([x], output) for output in outputs]
fn_fortran  = lambda xx: [fn_fortran(xx) for fn_fortran in fns_fortran]
```


```python
for y in fn_numpy(xx):
    plot(xx, y)
legend(['$R_{31}$', "$R'_{31}$"])
```


```python
%timeit fn_numpy(xx)
```

    1000 loops, best of 3: 1.6 ms per loop



```python
%timeit fn_fortran(xx)
```

    1000 loops, best of 3: 1.29 ms per loop



```python

```

5cbe17bb0975c086126225643de384b3c395281d
ipynb
Jupyter Notebook
tutorial_exercises/code-generation.ipynb
gvvynplaine/scipy-2016-tutorial
aa417427a1de2dcab2a9640b631b809d525d7929
BSD-3-Clause
2016-06-21T21:11:02.000Z
2021-02-04T07:51:03.000Z
tutorial_exercises/code-generation.ipynb
gvvynplaine/scipy-2016-tutorial
aa417427a1de2dcab2a9640b631b809d525d7929
BSD-3-Clause
2016-07-02T20:24:06.000Z
2016-07-11T11:31:44.000Z
tutorial_exercises/code-generation.ipynb
gvvynplaine/scipy-2016-tutorial
aa417427a1de2dcab2a9640b631b809d525d7929
BSD-3-Clause
2016-06-25T09:04:24.000Z
2021-08-09T06:46:01.000Z
Qwen/Qwen-72B
1. YES
2. YES