IPython speaks many languages

Insert a joke about Glossolalia and snakes.

Run commands in bash and get useful representations back:


In [ ]:
files = !ls
files

or run multiple lines in a cell that is all bash


In [ ]:
%%bash
uname -a
echo $PWD

Cython

Cython is an optimising static compiler for both the Python programming language and the extended Cython programming language (based on Pyrex). It makes writing C extensions for Python as easy as Python itself.

Quasi random numbers, Tim's knowledge on wrapping C/C++ libraries for easy use from python

TL;DR: use python syntax, get C speed.

Load the cython extension. Read more about ipython extensions


In [ ]:
# requires `conda install cython`
%load_ext Cython

In [ ]:
def f(x):
    return x**2-x

def integrate_f(a, b, N):
    s = 0; dx = (b-a)/N
    for i in range(N):
        s += f(a+i*dx)
    return s * dx

In [ ]:
%%cython
cdef double fcy(double x) except? -2:
    return x**2-x

def integrate_fcy(double a, double b, int N):
    cdef int i
    cdef double s, dx
    s = 0; dx = (b-a)/N
    for i in range(N):
        s += fcy(a+i*dx)
    return s * dx

In [ ]:
%timeit integrate_f(0, 1, 100)
%timeit integrate_fcy(0, 1, 100)

Getting help

What options does the cython magic have?


In [ ]:
%%cython?

In [ ]:
%%cython -lm
# Link the m library (like g++ linker argument)
from libc.math cimport sin
print 'sin(1)=', sin(1)

In [ ]:
%%cython -a
cdef double fcy(double x) except? -2:
    return x**2-x

def integrate_fcy(double a, double b, int N):
    cdef int i
    cdef double s, dx
    s = 0; dx = (b-a)/N
    for i in range(N):
        s += fcy(a+i*dx)
    return s * dx