# Cython¶

Christian Elsasser (che@physik.uzh.ch)

The content of this lecture might be distributed under CC by-sa.

## An introductionnary example - Fibonacci numbers¶

In [1]:

    def fib0(n):
        a,b=1,1
        for i in range(n):
            a,b=a+b,a
        return a

In [2]:

    fib0(5)

Out[2]:

    13

In [3]:

    fib0(6)

Out[3]:

    21

In [4]:

    %timeit fib0(10000)

    1.8 ms ± 72.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [5]:

    import cython

In [6]:

    %load_ext Cython

In [7]:

    %%cython
    def helloWorld():
        print("Hello, World!")

In [8]:

    helloWorld

Out[8]:

    <function _cython_magic_1e94ac26f08bef41582c79918a5fcf70.helloWorld>

In [9]:

    helloWorld()

    Hello, World!

In [10]:

    %%cython
    def fib1(n):
        a,b=1,1
        for i in range(n):
            a,b=a+b,a
        return a

In [11]:

    fib1

Out[11]:

    <function _cython_magic_c1e0012bfb99fd5003ebad8c0651b2b0.fib1>

In [12]:

    fib1(5)

Out[12]:

    13

In [13]:

    %timeit fib1(10000)

    1.69 ms ± 113 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [14]:

    %%cython
    def fib2(int n):
        cdef int a,b,i
        a,b=1,1
        for i in range(n):
            a,b=a+b,a
        return a

In [15]:

    fib2

Out[15]:

    <function _cython_magic_f7490ba68998cfb935013db37fe7a73f.fib2>

In [16]:

    fib2(5)

Out[16]:

    13

In [17]:

    %timeit fib2(10000)

    2.26 µs ± 33 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

## Second Example - Numerical integration¶

In [18]:

    %%cython -a

    from math import sin,exp

    def f0(double x):
        return sin(x)*exp(-x)

    def integrate0(double a,double b,int N):
        cdef double dx,s
        cdef int i
        dx = (b-a)/N
        s = 0.0
        for i in range(N):
            s+=f0(a+(i+0.5)*dx)
        return s*dx

Out[18]:
Cython: _cython_magic_8b497ee17d3d8e2620ca83c3610c0069.pyx

Generated by Cython 0.29.23

Yellow lines hint at Python interaction.
Click on a line that starts with a "`+`" to see the C code that Cython generated for it.

     01:

    +02: from math import sin,exp

      __pyx_t_1 = PyList_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_1);
      __Pyx_INCREF(__pyx_n_s_sin);
      __Pyx_GIVEREF(__pyx_n_s_sin);
      PyList_SET_ITEM(__pyx_t_1, 0, __pyx_n_s_sin);
      __Pyx_INCREF(__pyx_n_s_exp);
      __Pyx_GIVEREF(__pyx_n_s_exp);
      PyList_SET_ITEM(__pyx_t_1, 1, __pyx_n_s_exp);
      __pyx_t_2 = __Pyx_Import(__pyx_n_s_math, __pyx_t_1, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 2, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_2);
      __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
      __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_sin); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_1);
      if (PyDict_SetItem(__pyx_d, __pyx_n_s_sin, __pyx_t_1) < 0) __PYX_ERR(0, 2, __pyx_L1_error)
      __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
      __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_exp); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_1);
      if (PyDict_SetItem(__pyx_d, __pyx_n_s_exp, __pyx_t_1) < 0) __PYX_ERR(0, 2, __pyx_L1_error)
      __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
      __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;

     03:

    +04: def f0(double x):

    /* Python wrapper */
    static PyObject *__pyx_pw_46_cython_magic_8b497ee17d3d8e2620ca83c3610c0069_1f0(PyObject *__pyx_self, PyObject *__pyx_arg_x); /*proto*/
    static PyMethodDef __pyx_mdef_46_cython_magic_8b497ee17d3d8e2620ca83c3610c0069_1f0 = {"f0", (PyCFunction)__pyx_pw_46_cython_magic_8b497ee17d3d8e2620ca83c3610c0069_1f0, METH_O, 0};
    static PyObject *__pyx_pw_46_cython_magic_8b497ee17d3d8e2620ca83c3610c0069_1f0(PyObject *__pyx_self, PyObject *__pyx_arg_x) {
      double __pyx_v_x;
      PyObject *__pyx_r = 0;
      __Pyx_RefNannyDeclarations
      __Pyx_RefNannySetupContext("f0 (wrapper)", 0);
      assert(__pyx_arg_x); {
        __pyx_v_x = __pyx_PyFloat_AsDouble(__pyx_arg_x); if (unlikely((__pyx_v_x == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 4, __pyx_L3_error)
      }
      goto __pyx_L4_argument_unpacking_done;
      __pyx_L3_error:;
      __Pyx_AddTraceback("_cython_magic_8b497ee17d3d8e2620ca83c3610c0069.f0", __pyx_clineno, __pyx_lineno, __pyx_filename);
      __Pyx_RefNannyFinishContext();
      return NULL;
      __pyx_L4_argument_unpacking_done:;
      __pyx_r = __pyx_pf_46_cython_magic_8b497ee17d3d8e2620ca83c3610c0069_f0(__pyx_self, ((double)__pyx_v_x));
      int __pyx_lineno = 0;
      const char *__pyx_filename = NULL;
      int __pyx_clineno = 0;

      /* function exit code */
      __Pyx_RefNannyFinishContext();
      return __pyx_r;
    }

    static PyObject *__pyx_pf_46_cython_magic_8b497ee17d3d8e2620ca83c3610c0069_f0(CYTHON_UNUSED PyObject *__pyx_self, double __pyx_v_x) {
      PyObject *__pyx_r = NULL;
      __Pyx_RefNannyDeclarations
      __Pyx_RefNannySetupContext("f0", 0);
    /* … */
      /* function exit code */
      __pyx_L1_error:;
      __Pyx_XDECREF(__pyx_t_1);
      __Pyx_XDECREF(__pyx_t_2);
      __Pyx_XDECREF(__pyx_t_3);
      __Pyx_XDECREF(__pyx_t_4);
      __Pyx_XDECREF(__pyx_t_5);
      __Pyx_AddTraceback("_cython_magic_8b497ee17d3d8e2620ca83c3610c0069.f0", __pyx_clineno, __pyx_lineno, __pyx_filename);
      __pyx_r = NULL;
      __pyx_L0:;
      __Pyx_XGIVEREF(__pyx_r);
      __Pyx_RefNannyFinishContext();
      return __pyx_r;
    }
    /* … */
      __pyx_tuple_ = PyTuple_Pack(2, __pyx_n_s_x, __pyx_n_s_x); if (unlikely(!__pyx_tuple_)) __PYX_ERR(0, 4, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_tuple_);
      __Pyx_GIVEREF(__pyx_tuple_);
    /* … */
      __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_46_cython_magic_8b497ee17d3d8e2620ca83c3610c0069_1f0, NULL, __pyx_n_s_cython_magic_8b497ee17d3d8e2620); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 4, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_2);
      if (PyDict_SetItem(__pyx_d, __pyx_n_s_f0, __pyx_t_2) < 0) __PYX_ERR(0, 4, __pyx_L1_error)
      __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
      __pyx_codeobj__2 = (PyObject*)__Pyx_PyCode_New(1, 0, 2, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple_, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Users_che_ipython_cython__cytho, __pyx_n_s_f0, 4, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__2)) __PYX_ERR(0, 4, __pyx_L1_error)

    +05:     return sin(x)*exp(-x)

      __Pyx_XDECREF(__pyx_r);
      __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_sin); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 5, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_2);
      __pyx_t_3 = PyFloat_FromDouble(__pyx_v_x); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 5, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_3);
      __pyx_t_4 = NULL;
      if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) {
        __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_2);
        if (likely(__pyx_t_4)) {
          PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2);
          __Pyx_INCREF(__pyx_t_4);
          __Pyx_INCREF(function);
          __Pyx_DECREF_SET(__pyx_t_2, function);
        }
      }
      __pyx_t_1 = (__pyx_t_4) ? __Pyx_PyObject_Call2Args(__pyx_t_2, __pyx_t_4, __pyx_t_3) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_3);
      __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0;
      __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
      if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 5, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_1);
      __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
      __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_exp); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 5, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_3);
      __pyx_t_4 = PyFloat_FromDouble((-__pyx_v_x)); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 5, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_4);
      __pyx_t_5 = NULL;
      if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) {
        __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_3);
        if (likely(__pyx_t_5)) {
          PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3);
          __Pyx_INCREF(__pyx_t_5);
          __Pyx_INCREF(function);
          __Pyx_DECREF_SET(__pyx_t_3, function);
        }
      }
      __pyx_t_2 = (__pyx_t_5) ? __Pyx_PyObject_Call2Args(__pyx_t_3, __pyx_t_5, __pyx_t_4) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_4);
      __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0;
      __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
      if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 5, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_2);
      __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
      __pyx_t_3 = PyNumber_Multiply(__pyx_t_1, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 5, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_3);
      __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
      __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
      __pyx_r = __pyx_t_3;
      __pyx_t_3 = 0;
      goto __pyx_L0;

     06:

    +07: def integrate0(double a,double b,int N):

    /* Python wrapper */
    static PyObject *__pyx_pw_46_cython_magic_8b497ee17d3d8e2620ca83c3610c0069_3integrate0(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
    static PyMethodDef __pyx_mdef_46_cython_magic_8b497ee17d3d8e2620ca83c3610c0069_3integrate0 = {"integrate0", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_46_cython_magic_8b497ee17d3d8e2620ca83c3610c0069_3integrate0, METH_VARARGS|METH_KEYWORDS, 0};
    static PyObject *__pyx_pw_46_cython_magic_8b497ee17d3d8e2620ca83c3610c0069_3integrate0(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
      double __pyx_v_a;
      double __pyx_v_b;
      int __pyx_v_N;
      PyObject *__pyx_r = 0;
      __Pyx_RefNannyDeclarations
      __Pyx_RefNannySetupContext("integrate0 (wrapper)", 0);
      {
        static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_a,&__pyx_n_s_b,&__pyx_n_s_N,0};
        PyObject* values[3] = {0,0,0};
        if (unlikely(__pyx_kwds)) {
          Py_ssize_t kw_args;
          const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args);
          switch (pos_args) {
            case  3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2);
            CYTHON_FALLTHROUGH;
            case  2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1);
            CYTHON_FALLTHROUGH;
            case  1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
            CYTHON_FALLTHROUGH;
            case  0: break;
            default: goto __pyx_L5_argtuple_error;
          }
          kw_args = PyDict_Size(__pyx_kwds);
          switch (pos_args) {
            case  0:
            if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_a)) != 0)) kw_args--;
            else goto __pyx_L5_argtuple_error;
            CYTHON_FALLTHROUGH;
            case  1:
            if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_b)) != 0)) kw_args--;
            else {
              __Pyx_RaiseArgtupleInvalid("integrate0", 1, 3, 3, 1); __PYX_ERR(0, 7, __pyx_L3_error)
            }
            CYTHON_FALLTHROUGH;
            case  2:
            if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_N)) != 0)) kw_args--;
            else {
              __Pyx_RaiseArgtupleInvalid("integrate0", 1, 3, 3, 2); __PYX_ERR(0, 7, __pyx_L3_error)
            }
          }
          if (unlikely(kw_args > 0)) {
            if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "integrate0") < 0)) __PYX_ERR(0, 7, __pyx_L3_error)
          }
        } else if (PyTuple_GET_SIZE(__pyx_args) != 3) {
          goto __pyx_L5_argtuple_error;
        } else {
          values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
          values[1] = PyTuple_GET_ITEM(__pyx_args, 1);
          values[2] = PyTuple_GET_ITEM(__pyx_args, 2);
        }
        __pyx_v_a = __pyx_PyFloat_AsDouble(values[0]); if (unlikely((__pyx_v_a == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 7, __pyx_L3_error)
        __pyx_v_b = __pyx_PyFloat_AsDouble(values[1]); if (unlikely((__pyx_v_b == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 7, __pyx_L3_error)
        __pyx_v_N = __Pyx_PyInt_As_int(values[2]); if (unlikely((__pyx_v_N == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 7, __pyx_L3_error)
      }
      goto __pyx_L4_argument_unpacking_done;
      __pyx_L5_argtuple_error:;
      __Pyx_RaiseArgtupleInvalid("integrate0", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 7, __pyx_L3_error)
      __pyx_L3_error:;
      __Pyx_AddTraceback("_cython_magic_8b497ee17d3d8e2620ca83c3610c0069.integrate0", __pyx_clineno, __pyx_lineno, __pyx_filename);
      __Pyx_RefNannyFinishContext();
      return NULL;
      __pyx_L4_argument_unpacking_done:;
      __pyx_r = __pyx_pf_46_cython_magic_8b497ee17d3d8e2620ca83c3610c0069_2integrate0(__pyx_self, __pyx_v_a, __pyx_v_b, __pyx_v_N);
      int __pyx_lineno = 0;
      const char *__pyx_filename = NULL;
      int __pyx_clineno = 0;

      /* function exit code */
      __Pyx_RefNannyFinishContext();
      return __pyx_r;
    }

    static PyObject *__pyx_pf_46_cython_magic_8b497ee17d3d8e2620ca83c3610c0069_2integrate0(CYTHON_UNUSED PyObject *__pyx_self, double __pyx_v_a, double __pyx_v_b, int __pyx_v_N) {
      double __pyx_v_dx;
      double __pyx_v_s;
      int __pyx_v_i;
      PyObject *__pyx_r = NULL;
      __Pyx_RefNannyDeclarations
      __Pyx_RefNannySetupContext("integrate0", 0);
    /* … */
      /* function exit code */
      __pyx_L1_error:;
      __Pyx_XDECREF(__pyx_t_5);
      __Pyx_XDECREF(__pyx_t_6);
      __Pyx_XDECREF(__pyx_t_7);
      __Pyx_XDECREF(__pyx_t_8);
      __Pyx_XDECREF(__pyx_t_9);
      __Pyx_AddTraceback("_cython_magic_8b497ee17d3d8e2620ca83c3610c0069.integrate0", __pyx_clineno, __pyx_lineno, __pyx_filename);
      __pyx_r = NULL;
      __pyx_L0:;
      __Pyx_XGIVEREF(__pyx_r);
      __Pyx_RefNannyFinishContext();
      return __pyx_r;
    }
    /* … */
      __pyx_tuple__3 = PyTuple_Pack(6, __pyx_n_s_a, __pyx_n_s_b, __pyx_n_s_N, __pyx_n_s_dx, __pyx_n_s_s, __pyx_n_s_i); if (unlikely(!__pyx_tuple__3)) __PYX_ERR(0, 7, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_tuple__3);
      __Pyx_GIVEREF(__pyx_tuple__3);
    /* … */
      __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_46_cython_magic_8b497ee17d3d8e2620ca83c3610c0069_3integrate0, NULL, __pyx_n_s_cython_magic_8b497ee17d3d8e2620); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 7, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_2);
      if (PyDict_SetItem(__pyx_d, __pyx_n_s_integrate0, __pyx_t_2) < 0) __PYX_ERR(0, 7, __pyx_L1_error)
      __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;

     08:     cdef double dx,s

     09:     cdef int i

    +10:     dx = (b-a)/N

      __pyx_t_1 = (__pyx_v_b - __pyx_v_a);
      if (unlikely(__pyx_v_N == 0)) {
        PyErr_SetString(PyExc_ZeroDivisionError, "float division");
        __PYX_ERR(0, 10, __pyx_L1_error)
      }
      __pyx_v_dx = (__pyx_t_1 / ((double)__pyx_v_N));

    +11:     s = 0.0

      __pyx_v_s = 0.0;

    +12:     for i in range(N):

      __pyx_t_2 = __pyx_v_N;
      __pyx_t_3 = __pyx_t_2;
      for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) {
        __pyx_v_i = __pyx_t_4;

    +13:         s+=f0(a+(i+0.5)*dx)

        __pyx_t_5 = PyFloat_FromDouble(__pyx_v_s); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 13, __pyx_L1_error)
        __Pyx_GOTREF(__pyx_t_5);
        __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_n_s_f0); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 13, __pyx_L1_error)
        __Pyx_GOTREF(__pyx_t_7);
        __pyx_t_8 = PyFloat_FromDouble((__pyx_v_a + ((__pyx_v_i + 0.5) * __pyx_v_dx))); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 13, __pyx_L1_error)
        __Pyx_GOTREF(__pyx_t_8);
        __pyx_t_9 = NULL;
        if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_7))) {
          __pyx_t_9 = PyMethod_GET_SELF(__pyx_t_7);
          if (likely(__pyx_t_9)) {
            PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_7);
            __Pyx_INCREF(__pyx_t_9);
            __Pyx_INCREF(function);
            __Pyx_DECREF_SET(__pyx_t_7, function);
          }
        }
        __pyx_t_6 = (__pyx_t_9) ? __Pyx_PyObject_Call2Args(__pyx_t_7, __pyx_t_9, __pyx_t_8) : __Pyx_PyObject_CallOneArg(__pyx_t_7, __pyx_t_8);
        __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0;
        __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
        if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 13, __pyx_L1_error)
        __Pyx_GOTREF(__pyx_t_6);
        __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0;
        __pyx_t_7 = PyNumber_InPlaceAdd(__pyx_t_5, __pyx_t_6); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 13, __pyx_L1_error)
        __Pyx_GOTREF(__pyx_t_7);
        __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
        __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0;
        __pyx_t_1 = __pyx_PyFloat_AsDouble(__pyx_t_7); if (unlikely((__pyx_t_1 == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 13, __pyx_L1_error)
        __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0;
        __pyx_v_s = __pyx_t_1;
      }

    +14:     return s*dx

      __Pyx_XDECREF(__pyx_r);
      __pyx_t_7 = PyFloat_FromDouble((__pyx_v_s * __pyx_v_dx)); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 14, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_7);
      __pyx_r = __pyx_t_7;
      __pyx_t_7 = 0;
      goto __pyx_L0;

In [19]:

    from math import pi

In [20]:

    integrate0(0.0,pi,1000000)

Out[20]:

    0.5216069591323289

In [21]:

    %timeit integrate0(0.0,pi,1000000)

    110 ms ± 6.57 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [22]:

    %%cython -a

    from math import sin,exp

    cdef double f1(double x):
        return sin(x)*exp(-x)

    def integrate1(double a,double b,int N):
        cdef double dx,s
        cdef int i
        dx = (b-a)/N
        s = 0.0
        for i in range(N):
            s+=f1(a+(i+0.5)*dx)
        return s*dx

Out[22]:
Cython: _cython_magic_eced0072c301be2e2b958ffdaca99c84.pyx

Generated by Cython 0.29.23

Yellow lines hint at Python interaction.
Click on a line that starts with a "`+`" to see the C code that Cython generated for it.

     01:

    +02: from math import sin,exp

      __pyx_t_1 = PyList_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_1);
      __Pyx_INCREF(__pyx_n_s_sin);
      __Pyx_GIVEREF(__pyx_n_s_sin);
      PyList_SET_ITEM(__pyx_t_1, 0, __pyx_n_s_sin);
      __Pyx_INCREF(__pyx_n_s_exp);
      __Pyx_GIVEREF(__pyx_n_s_exp);
      PyList_SET_ITEM(__pyx_t_1, 1, __pyx_n_s_exp);
      __pyx_t_2 = __Pyx_Import(__pyx_n_s_math, __pyx_t_1, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 2, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_2);
      __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
      __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_sin); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_1);
      if (PyDict_SetItem(__pyx_d, __pyx_n_s_sin, __pyx_t_1) < 0) __PYX_ERR(0, 2, __pyx_L1_error)
      __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
      __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_exp); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_1);
      if (PyDict_SetItem(__pyx_d, __pyx_n_s_exp, __pyx_t_1) < 0) __PYX_ERR(0, 2, __pyx_L1_error)
      __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
      __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;

     03:

    +04: cdef double f1(double x):

    static double __pyx_f_46_cython_magic_eced0072c301be2e2b958ffdaca99c84_f1(double __pyx_v_x) {
      double __pyx_r;
      __Pyx_RefNannyDeclarations
      __Pyx_RefNannySetupContext("f1", 0);
    /* … */
      /* function exit code */
      __pyx_L1_error:;
      __Pyx_XDECREF(__pyx_t_1);
      __Pyx_XDECREF(__pyx_t_2);
      __Pyx_XDECREF(__pyx_t_3);
      __Pyx_XDECREF(__pyx_t_4);
      __Pyx_XDECREF(__pyx_t_5);
      __Pyx_WriteUnraisable("_cython_magic_eced0072c301be2e2b958ffdaca99c84.f1", __pyx_clineno, __pyx_lineno, __pyx_filename, 1, 0);
      __pyx_r = 0;
      __pyx_L0:;
      __Pyx_RefNannyFinishContext();
      return __pyx_r;
    }

    +05:     return sin(x)*exp(-x)

      __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_sin); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 5, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_2);
      __pyx_t_3 = PyFloat_FromDouble(__pyx_v_x); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 5, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_3);
      __pyx_t_4 = NULL;
      if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) {
        __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_2);
        if (likely(__pyx_t_4)) {
          PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2);
          __Pyx_INCREF(__pyx_t_4);
          __Pyx_INCREF(function);
          __Pyx_DECREF_SET(__pyx_t_2, function);
        }
      }
      __pyx_t_1 = (__pyx_t_4) ? __Pyx_PyObject_Call2Args(__pyx_t_2, __pyx_t_4, __pyx_t_3) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_3);
      __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0;
      __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
      if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 5, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_1);
      __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
      __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_exp); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 5, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_3);
      __pyx_t_4 = PyFloat_FromDouble((-__pyx_v_x)); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 5, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_4);
      __pyx_t_5 = NULL;
      if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) {
        __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_3);
        if (likely(__pyx_t_5)) {
          PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3);
          __Pyx_INCREF(__pyx_t_5);
          __Pyx_INCREF(function);
          __Pyx_DECREF_SET(__pyx_t_3, function);
        }
      }
      __pyx_t_2 = (__pyx_t_5) ? __Pyx_PyObject_Call2Args(__pyx_t_3, __pyx_t_5, __pyx_t_4) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_4);
      __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0;
      __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
      if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 5, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_2);
      __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
      __pyx_t_3 = PyNumber_Multiply(__pyx_t_1, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 5, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_3);
      __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
      __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
      __pyx_t_6 = __pyx_PyFloat_AsDouble(__pyx_t_3); if (unlikely((__pyx_t_6 == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 5, __pyx_L1_error)
      __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
      __pyx_r = __pyx_t_6;
      goto __pyx_L0;

     06:

    +07: def integrate1(double a,double b,int N):

    /* Python wrapper */
    static PyObject *__pyx_pw_46_cython_magic_eced0072c301be2e2b958ffdaca99c84_1integrate1(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
    static PyMethodDef __pyx_mdef_46_cython_magic_eced0072c301be2e2b958ffdaca99c84_1integrate1 = {"integrate1", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_46_cython_magic_eced0072c301be2e2b958ffdaca99c84_1integrate1, METH_VARARGS|METH_KEYWORDS, 0};
    static PyObject *__pyx_pw_46_cython_magic_eced0072c301be2e2b958ffdaca99c84_1integrate1(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
      double __pyx_v_a;
      double __pyx_v_b;
      int __pyx_v_N;
      PyObject *__pyx_r = 0;
      __Pyx_RefNannyDeclarations
      __Pyx_RefNannySetupContext("integrate1 (wrapper)", 0);
      {
        static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_a,&__pyx_n_s_b,&__pyx_n_s_N,0};
        PyObject* values[3] = {0,0,0};
        if (unlikely(__pyx_kwds)) {
          Py_ssize_t kw_args;
          const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args);
          switch (pos_args) {
            case  3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2);
            CYTHON_FALLTHROUGH;
            case  2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1);
            CYTHON_FALLTHROUGH;
            case  1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
            CYTHON_FALLTHROUGH;
            case  0: break;
            default: goto __pyx_L5_argtuple_error;
          }
          kw_args = PyDict_Size(__pyx_kwds);
          switch (pos_args) {
            case  0:
            if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_a)) != 0)) kw_args--;
            else goto __pyx_L5_argtuple_error;
            CYTHON_FALLTHROUGH;
            case  1:
            if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_b)) != 0)) kw_args--;
            else {
              __Pyx_RaiseArgtupleInvalid("integrate1", 1, 3, 3, 1); __PYX_ERR(0, 7, __pyx_L3_error)
            }
            CYTHON_FALLTHROUGH;
            case  2:
            if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_N)) != 0)) kw_args--;
            else {
              __Pyx_RaiseArgtupleInvalid("integrate1", 1, 3, 3, 2); __PYX_ERR(0, 7, __pyx_L3_error)
            }
          }
          if (unlikely(kw_args > 0)) {
            if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "integrate1") < 0)) __PYX_ERR(0, 7, __pyx_L3_error)
          }
        } else if (PyTuple_GET_SIZE(__pyx_args) != 3) {
          goto __pyx_L5_argtuple_error;
        } else {
          values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
          values[1] = PyTuple_GET_ITEM(__pyx_args, 1);
          values[2] = PyTuple_GET_ITEM(__pyx_args, 2);
        }
        __pyx_v_a = __pyx_PyFloat_AsDouble(values[0]); if (unlikely((__pyx_v_a == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 7, __pyx_L3_error)
        __pyx_v_b = __pyx_PyFloat_AsDouble(values[1]); if (unlikely((__pyx_v_b == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 7, __pyx_L3_error)
        __pyx_v_N = __Pyx_PyInt_As_int(values[2]); if (unlikely((__pyx_v_N == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 7, __pyx_L3_error)
      }
      goto __pyx_L4_argument_unpacking_done;
      __pyx_L5_argtuple_error:;
      __Pyx_RaiseArgtupleInvalid("integrate1", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 7, __pyx_L3_error)
      __pyx_L3_error:;
      __Pyx_AddTraceback("_cython_magic_eced0072c301be2e2b958ffdaca99c84.integrate1", __pyx_clineno, __pyx_lineno, __pyx_filename);
      __Pyx_RefNannyFinishContext();
      return NULL;
      __pyx_L4_argument_unpacking_done:;
      __pyx_r = __pyx_pf_46_cython_magic_eced0072c301be2e2b958ffdaca99c84_integrate1(__pyx_self, __pyx_v_a, __pyx_v_b, __pyx_v_N);
      int __pyx_lineno = 0;
      const char *__pyx_filename = NULL;
      int __pyx_clineno = 0;

      /* function exit code */
      __Pyx_RefNannyFinishContext();
      return __pyx_r;
    }

    static PyObject *__pyx_pf_46_cython_magic_eced0072c301be2e2b958ffdaca99c84_integrate1(CYTHON_UNUSED PyObject *__pyx_self, double __pyx_v_a, double __pyx_v_b, int __pyx_v_N) {
      double __pyx_v_dx;
      double __pyx_v_s;
      int __pyx_v_i;
      PyObject *__pyx_r = NULL;
      __Pyx_RefNannyDeclarations
      __Pyx_RefNannySetupContext("integrate1", 0);
    /* … */
      /* function exit code */
      __pyx_L1_error:;
      __Pyx_XDECREF(__pyx_t_5);
      __Pyx_AddTraceback("_cython_magic_eced0072c301be2e2b958ffdaca99c84.integrate1", __pyx_clineno, __pyx_lineno, __pyx_filename);
      __pyx_r = NULL;
      __pyx_L0:;
      __Pyx_XGIVEREF(__pyx_r);
      __Pyx_RefNannyFinishContext();
      return __pyx_r;
    }
    /* … */
      __pyx_tuple_ = PyTuple_Pack(6, __pyx_n_s_a, __pyx_n_s_b, __pyx_n_s_N, __pyx_n_s_dx, __pyx_n_s_s, __pyx_n_s_i); if (unlikely(!__pyx_tuple_)) __PYX_ERR(0, 7, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_tuple_);
      __Pyx_GIVEREF(__pyx_tuple_);
    /* … */
      __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_46_cython_magic_eced0072c301be2e2b958ffdaca99c84_1integrate1, NULL, __pyx_n_s_cython_magic_eced0072c301be2e2b); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 7, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_2);
      if (PyDict_SetItem(__pyx_d, __pyx_n_s_integrate1, __pyx_t_2) < 0) __PYX_ERR(0, 7, __pyx_L1_error)
      __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;

     08:     cdef double dx,s

     09:     cdef int i

    +10:     dx = (b-a)/N

      __pyx_t_1 = (__pyx_v_b - __pyx_v_a);
      if (unlikely(__pyx_v_N == 0)) {
        PyErr_SetString(PyExc_ZeroDivisionError, "float division");
        __PYX_ERR(0, 10, __pyx_L1_error)
      }
      __pyx_v_dx = (__pyx_t_1 / ((double)__pyx_v_N));

    +11:     s = 0.0

      __pyx_v_s = 0.0;

    +12:     for i in range(N):

      __pyx_t_2 = __pyx_v_N;
      __pyx_t_3 = __pyx_t_2;
      for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) {
        __pyx_v_i = __pyx_t_4;

    +13:         s+=f1(a+(i+0.5)*dx)

        __pyx_v_s = (__pyx_v_s + __pyx_f_46_cython_magic_eced0072c301be2e2b958ffdaca99c84_f1((__pyx_v_a + ((__pyx_v_i + 0.5) * __pyx_v_dx))));
      }

    +14:     return s*dx

      __Pyx_XDECREF(__pyx_r);
      __pyx_t_5 = PyFloat_FromDouble((__pyx_v_s * __pyx_v_dx)); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 14, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_5);
      __pyx_r = __pyx_t_5;
      __pyx_t_5 = 0;
      goto __pyx_L0;

In [23]:

    %timeit integrate1(0.0,pi,1000000)

    75.3 ms ± 3.44 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [24]:

    f1(5)

    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-24-c5ed7dd0edc1> in <module>
    ----> 1 f1(5)

    NameError: name 'f1' is not defined

In [25]:

    %%cython -a

    from libc.math cimport sin,exp

    cpdef double f2(double x):
        return sin(x)*exp(-x)

    def integrate2(double a,double b,int N):
        cdef double dx,s
        cdef int i
        dx = (b-a)/N
        s = 0.0
        for i in range(N):
            s+=f2(a+(i+0.5)*dx)
        return s*dx

Out[25]:
Cython: _cython_magic_665606de606cf891f26bfe4129a68677.pyx

Generated by Cython 0.29.23

Yellow lines hint at Python interaction.
Click on a line that starts with a "`+`" to see the C code that Cython generated for it.

     01:

     02: from libc.math cimport sin,exp

     03:

    +04: cpdef double f2(double x):

    static PyObject *__pyx_pw_46_cython_magic_665606de606cf891f26bfe4129a68677_1f2(PyObject *__pyx_self, PyObject *__pyx_arg_x); /*proto*/
    static double __pyx_f_46_cython_magic_665606de606cf891f26bfe4129a68677_f2(double __pyx_v_x, CYTHON_UNUSED int __pyx_skip_dispatch) {
      double __pyx_r;
      __Pyx_RefNannyDeclarations
      __Pyx_RefNannySetupContext("f2", 0);
    /* … */
      /* function exit code */
      __pyx_L0:;
      __Pyx_RefNannyFinishContext();
      return __pyx_r;
    }

    /* Python wrapper */
    static PyObject *__pyx_pw_46_cython_magic_665606de606cf891f26bfe4129a68677_1f2(PyObject *__pyx_self, PyObject *__pyx_arg_x); /*proto*/
    static PyObject *__pyx_pw_46_cython_magic_665606de606cf891f26bfe4129a68677_1f2(PyObject *__pyx_self, PyObject *__pyx_arg_x) {
      double __pyx_v_x;
      PyObject *__pyx_r = 0;
      __Pyx_RefNannyDeclarations
      __Pyx_RefNannySetupContext("f2 (wrapper)", 0);
      assert(__pyx_arg_x); {
        __pyx_v_x = __pyx_PyFloat_AsDouble(__pyx_arg_x); if (unlikely((__pyx_v_x == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 4, __pyx_L3_error)
      }
      goto __pyx_L4_argument_unpacking_done;
      __pyx_L3_error:;
      __Pyx_AddTraceback("_cython_magic_665606de606cf891f26bfe4129a68677.f2", __pyx_clineno, __pyx_lineno, __pyx_filename);
      __Pyx_RefNannyFinishContext();
      return NULL;
      __pyx_L4_argument_unpacking_done:;
      __pyx_r = __pyx_pf_46_cython_magic_665606de606cf891f26bfe4129a68677_f2(__pyx_self, ((double)__pyx_v_x));
      int __pyx_lineno = 0;
      const char *__pyx_filename = NULL;
      int __pyx_clineno = 0;

      /* function exit code */
      __Pyx_RefNannyFinishContext();
      return __pyx_r;
    }

    static PyObject *__pyx_pf_46_cython_magic_665606de606cf891f26bfe4129a68677_f2(CYTHON_UNUSED PyObject *__pyx_self, double __pyx_v_x) {
      PyObject *__pyx_r = NULL;
      __Pyx_RefNannyDeclarations
      __Pyx_RefNannySetupContext("f2", 0);
      __Pyx_XDECREF(__pyx_r);
      __pyx_t_1 = PyFloat_FromDouble(__pyx_f_46_cython_magic_665606de606cf891f26bfe4129a68677_f2(__pyx_v_x, 0)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 4, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_1);
      __pyx_r = __pyx_t_1;
      __pyx_t_1 = 0;
      goto __pyx_L0;

      /* function exit code */
      __pyx_L1_error:;
      __Pyx_XDECREF(__pyx_t_1);
      __Pyx_AddTraceback("_cython_magic_665606de606cf891f26bfe4129a68677.f2", __pyx_clineno, __pyx_lineno, __pyx_filename);
      __pyx_r = NULL;
      __pyx_L0:;
      __Pyx_XGIVEREF(__pyx_r);
      __Pyx_RefNannyFinishContext();
      return __pyx_r;
    }

    +05:     return sin(x)*exp(-x)

      __pyx_r = (sin(__pyx_v_x) * exp((-__pyx_v_x)));
      goto __pyx_L0;

     06:

    +07: def integrate2(double a,double b,int N):

    /* Python wrapper */
    static PyObject *__pyx_pw_46_cython_magic_665606de606cf891f26bfe4129a68677_3integrate2(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
    static PyMethodDef __pyx_mdef_46_cython_magic_665606de606cf891f26bfe4129a68677_3integrate2 = {"integrate2", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_46_cython_magic_665606de606cf891f26bfe4129a68677_3integrate2, METH_VARARGS|METH_KEYWORDS, 0};
    static PyObject *__pyx_pw_46_cython_magic_665606de606cf891f26bfe4129a68677_3integrate2(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
      double __pyx_v_a;
      double __pyx_v_b;
      int __pyx_v_N;
      PyObject *__pyx_r = 0;
      __Pyx_RefNannyDeclarations
      __Pyx_RefNannySetupContext("integrate2 (wrapper)", 0);
      {
        static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_a,&__pyx_n_s_b,&__pyx_n_s_N,0};
        PyObject* values[3] = {0,0,0};
        if (unlikely(__pyx_kwds)) {
          Py_ssize_t kw_args;
          const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args);
          switch (pos_args) {
            case  3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2);
            CYTHON_FALLTHROUGH;
            case  2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1);
            CYTHON_FALLTHROUGH;
            case  1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
            CYTHON_FALLTHROUGH;
            case  0: break;
            default: goto __pyx_L5_argtuple_error;
          }
          kw_args = PyDict_Size(__pyx_kwds);
          switch (pos_args) {
            case  0:
            if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_a)) != 0)) kw_args--;
            else goto __pyx_L5_argtuple_error;
            CYTHON_FALLTHROUGH;
            case  1:
            if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_b)) != 0)) kw_args--;
            else {
              __Pyx_RaiseArgtupleInvalid("integrate2", 1, 3, 3, 1); __PYX_ERR(0, 7, __pyx_L3_error)
            }
            CYTHON_FALLTHROUGH;
            case  2:
            if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_N)) != 0)) kw_args--;
            else {
              __Pyx_RaiseArgtupleInvalid("integrate2", 1, 3, 3, 2); __PYX_ERR(0, 7, __pyx_L3_error)
            }
          }
          if (unlikely(kw_args > 0)) {
            if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "integrate2") < 0)) __PYX_ERR(0, 7, __pyx_L3_error)
          }
        } else if (PyTuple_GET_SIZE(__pyx_args) != 3) {
          goto __pyx_L5_argtuple_error;
        } else {
          values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
          values[1] = PyTuple_GET_ITEM(__pyx_args, 1);
          values[2] = PyTuple_GET_ITEM(__pyx_args, 2);
        }
        __pyx_v_a = __pyx_PyFloat_AsDouble(values[0]); if (unlikely((__pyx_v_a == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 7, __pyx_L3_error)
        __pyx_v_b = __pyx_PyFloat_AsDouble(values[1]); if (unlikely((__pyx_v_b == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 7, __pyx_L3_error)
        __pyx_v_N = __Pyx_PyInt_As_int(values[2]); if (unlikely((__pyx_v_N == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 7, __pyx_L3_error)
      }
      goto __pyx_L4_argument_unpacking_done;
      __pyx_L5_argtuple_error:;
      __Pyx_RaiseArgtupleInvalid("integrate2", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 7, __pyx_L3_error)
      __pyx_L3_error:;
      __Pyx_AddTraceback("_cython_magic_665606de606cf891f26bfe4129a68677.integrate2", __pyx_clineno, __pyx_lineno, __pyx_filename);
      __Pyx_RefNannyFinishContext();
      return NULL;
      __pyx_L4_argument_unpacking_done:;
      __pyx_r = __pyx_pf_46_cython_magic_665606de606cf891f26bfe4129a68677_2integrate2(__pyx_self, __pyx_v_a, __pyx_v_b, __pyx_v_N);
      int __pyx_lineno = 0;
      const char *__pyx_filename = NULL;
      int __pyx_clineno = 0;

      /* function exit code */
      __Pyx_RefNannyFinishContext();
      return __pyx_r;
    }

    static PyObject *__pyx_pf_46_cython_magic_665606de606cf891f26bfe4129a68677_2integrate2(CYTHON_UNUSED PyObject *__pyx_self, double __pyx_v_a, double __pyx_v_b, int __pyx_v_N) {
      double __pyx_v_dx;
      double __pyx_v_s;
      int __pyx_v_i;
      PyObject *__pyx_r = NULL;
      __Pyx_RefNannyDeclarations
      __Pyx_RefNannySetupContext("integrate2", 0);
    /* … */
      /* function exit code */
      __pyx_L1_error:;
      __Pyx_XDECREF(__pyx_t_5);
      __Pyx_AddTraceback("_cython_magic_665606de606cf891f26bfe4129a68677.integrate2", __pyx_clineno, __pyx_lineno, __pyx_filename);
      __pyx_r = NULL;
      __pyx_L0:;
      __Pyx_XGIVEREF(__pyx_r);
      __Pyx_RefNannyFinishContext();
      return __pyx_r;
    }
    /* … */
      __pyx_tuple_ = PyTuple_Pack(6, __pyx_n_s_a, __pyx_n_s_b, __pyx_n_s_N, __pyx_n_s_dx, __pyx_n_s_s, __pyx_n_s_i); if (unlikely(!__pyx_tuple_)) __PYX_ERR(0, 7, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_tuple_);
      __Pyx_GIVEREF(__pyx_tuple_);
    /* … */
      __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_46_cython_magic_665606de606cf891f26bfe4129a68677_3integrate2, NULL, __pyx_n_s_cython_magic_665606de606cf891f2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 7, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_1);
      if (PyDict_SetItem(__pyx_d, __pyx_n_s_integrate2, __pyx_t_1) < 0) __PYX_ERR(0, 7, __pyx_L1_error)
      __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;

     08:     cdef double dx,s

     09:     cdef int i

    +10:     dx = (b-a)/N

      __pyx_t_1 = (__pyx_v_b - __pyx_v_a);
      if (unlikely(__pyx_v_N == 0)) {
        PyErr_SetString(PyExc_ZeroDivisionError, "float division");
        __PYX_ERR(0, 10, __pyx_L1_error)
      }
      __pyx_v_dx = (__pyx_t_1 / ((double)__pyx_v_N));

    +11:     s = 0.0

      __pyx_v_s = 0.0;

    +12:     for i in range(N):

      __pyx_t_2 = __pyx_v_N;
      __pyx_t_3 = __pyx_t_2;
      for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) {
        __pyx_v_i = __pyx_t_4;

    +13:         s+=f2(a+(i+0.5)*dx)

        __pyx_v_s = (__pyx_v_s + __pyx_f_46_cython_magic_665606de606cf891f26bfe4129a68677_f2((__pyx_v_a + ((__pyx_v_i + 0.5) * __pyx_v_dx)), 0));
      }

    +14:     return s*dx

      __Pyx_XDECREF(__pyx_r);
      __pyx_t_5 = PyFloat_FromDouble((__pyx_v_s * __pyx_v_dx)); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 14, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_5);
      __pyx_r = __pyx_t_5;
      __pyx_t_5 = 0;
      goto __pyx_L0;

In [26]:

    %timeit integrate2(0.0,pi,1000000)

    12.9 ms ± 206 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [27]:

    import numpy as np

    def f3(x):
        return np.sin(x)*np.exp(-x)

    def integrate3(a,b,N):
        dx = (b-a)/N
        x = (np.arange(N)+0.5)*dx+a
        return np.sum(f3(x))*dx

In [28]:

    %timeit integrate3(0.0,pi,1000000)

    24.4 ms ± 823 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

## Cython and STL containers¶

In [29]:

    %%cython -+
    #distutils: language = c++
    from libcpp.vector cimport vector
    def manipulateVector(vector[double] v):
        v.push_back(42.0) # Equivalent to append for list in python
        return v

In [32]:

    manipulateVector([1,2,3,4])

Out[32]:

    [1.0, 2.0, 3.0, 4.0, 42.0]

## Cython and exceptions¶

In [33]:

    %%cython
    cpdef int raiseError():
        raise RuntimeError("A problem!")
        return 1

In [34]:

    raiseError()

    ---------------------------------------------------------------------------
    RuntimeError                              Traceback (most recent call last)
    RuntimeError: A problem!

    Exception ignored in: '_cython_magic_d0e8f1435a5eb19a70babd136537bece.raiseError'
    RuntimeError: A problem!

Out[34]:

    0

In [35]:

    %%cython
    cpdef int raiseErrorBetter() except *:
        raise RuntimeError("A problem!")
        return 1

In [36]:

    raiseErrorBetter()

    ---------------------------------------------------------------------------
    RuntimeError                              Traceback (most recent call last)
    <ipython-input-36-9e77aa258386> in <module>
    ----> 1 raiseErrorBetter()

    _cython_magic_a2582b4d6ac81cb772ebae3129bb42dc.pyx in _cython_magic_a2582b4d6ac81cb772ebae3129bb42dc.raiseErrorBetter()

    _cython_magic_a2582b4d6ac81cb772ebae3129bb42dc.pyx in _cython_magic_a2582b4d6ac81cb772ebae3129bb42dc.raiseErrorBetter()

    RuntimeError: A problem!

In [37]:

    try:
        raiseErrorBetter()
    except RuntimeError:
        print("Error caught")

    Error caught

In [38]:

    %%cython
    cpdef int raiseException(int n) except -1:
        # Assuming C function returning an integer; if -1 --> Error appeared
        return n

In [39]:

    raiseException(1)

Out[39]:

    1

In [40]:

    raiseException(-1)

    ---------------------------------------------------------------------------
    SystemError                               Traceback (most recent call last)
    <ipython-input-40-f1e17eec89ff> in <module>
    ----> 1 raiseException(-1)

    SystemError: <built-in function raiseException> returned NULL without setting an error

## Back to integration - Cython and Classes¶

In [41]:

    %%cython

    from libc.math cimport sin,exp

    cdef class Integrand(object):
        cpdef double evaluate(self,double x):
            raise NotImplementedError()

    cdef class SinExpFunction(Integrand):
        cpdef double evaluate(self,double x):
            return sin(x)*exp(-x)

    def integrate(Integrand f, double a, double b, int N):
        cdef int i
        cdef double dx,s
        dx = (b-a)/N
        s = 0.0
        for i in range(N):
            s += f.evaluate(a+(i+0.5)*dx)
        return s*dx

In [42]:

    f = SinExpFunction()

In [43]:

    import math

In [44]:

    %timeit integrate(f,0,math.pi,1000000)

    17 ms ± 305 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [45]:

    class Poly(Integrand):
        def evaluate(self,x):
            return 3*x-x**3

In [46]:

    g = Poly()
    integrate(g,0,math.pi,10000)

Out[46]:

    -9.5478660351052

In [47]:

    %timeit integrate(g,0,math.pi,1000000)

    187 ms ± 5.01 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [ ]: