The most basic form of code generation are the code printers. The convert SymPy expressions into the target language.
The most common languages are C, C++, Fortran, and Python, but over a dozen languages are supported. Here, we will quickly go over each supported language.
from sympy import *
init_printing()
Let us use the function $$|\sin(x^2)|.$$
x = symbols('x')
expr = abs(sin(x**2))
expr
ccode(expr)
fcode(expr)
julia_code(expr)
jscode(expr)
mathematica_code(expr)
octave_code(expr)
from sympy.printing.rust import rust_code
rust_code(expr)
rcode(expr)
from sympy.printing.cxxcode import cxxcode
cxxcode(expr)
Come up with a symbolic expression and try generating code for it in each language. Note, some languages don't support everything. What works and what doesn't? What things are the same across languages and what things are different?
Reminder: If you click a cell and press b
it will add a new cell below it.
# Write your answer here
One use case that works nicely with the Jupyter notebook is plotting mathematical functions using JavaScript plotting libraries. There are a variety of plotting libraries available and the notebook makes it relatively easy to use. Here we will use Chart.js to plot functions of a single variable. We can use the %%javascript
magic to type JavaScript directly into a notebook cell. In this cell we load in the Chart.js library:
%%javascript
require.config({
paths: {
'chartjs': '//cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart'
}
});
We've also prepared some Javascript to do the plotting. This code will take two mathematical expressions written in Javascript and plot the functions.
from scipy2017codegen.plotting import js_template
print(js_template.format(top_function='***fill me in!***',
bottom_function='***fill me in!***',
chart_id='***fill me in!***'))
Now SymPy functions can be plotted by filling in the two missing expressions in the above code and then calling the Javascript
display function on that code.
from IPython.display import Javascript
x = symbols('x')
f1 = sin(x)
f2 = cos(x)
Javascript(js_template.format(top_function=jscode(f1),
bottom_function=jscode(f2),
chart_id='sincos'))
Plot the equations below for top
and bottom
.
There are all kind of functions that can be plotted, but one particularly interesting set of functions are called the Batman Equations. We've provided the piecewise versions of these functions written in SymPy below. Try plotting these with the JS plotter we've created.
from scipy2017codegen.plotting import batman_equations
top, bottom = batman_equations()
top
bottom
# Write your answer here