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.
In [ ]:
from sympy import *
init_printing()
Let us use the function $$|\sin(x^2)|.$$
In [ ]:
x = symbols('x')
expr = abs(sin(x**2))
expr
In [ ]:
ccode(expr)
In [ ]:
fcode(expr)
In [ ]:
julia_code(expr)
In [ ]:
jscode(expr)
In [ ]:
mathematica_code(expr)
In [ ]:
octave_code(expr)
In [ ]:
from sympy.printing.rust import rust_code
rust_code(expr)
In [ ]:
rcode(expr)
In [ ]:
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.
In [ ]:
# Write your answer here
In [ ]:
In [ ]:
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:
In [ ]:
%%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.
In [ ]:
from scipy2017codegen.plotting import js_template
In [ ]:
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.
In [ ]:
from IPython.display import Javascript
In [ ]:
x = symbols('x')
f1 = sin(x)
f2 = cos(x)
In [ ]:
Javascript(js_template.format(top_function=jscode(f1),
bottom_function=jscode(f2),
chart_id='sincos'))
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.
In [ ]:
from scipy2017codegen.plotting import batman_equations
In [ ]:
top, bottom = batman_equations()
In [ ]:
top
In [ ]:
bottom
In [ ]:
# Write your answer here