Commit e858f582 authored by scoder's avatar scoder Committed by GitHub

Merge pull request #2331 from gabrieldemarmiesse/test_cdef_classes_3

Added tests for cdef_classes.rst. Part 3.
parents d88c784a 3b9873ff
from sin_of_square cimport Function, SinOfSquareFunction
def integrate(Function f, double a, double b, int N):
cdef int i
cdef double s, dx
if f is None:
raise ValueError("f cannot be None")
s = 0
dx = (b - a) / N
for i in range(N):
s += f.evaluate(a + i * dx)
return s * dx
print(integrate(SinOfSquareFunction(), 0, 1, 10000))
cdef class Function:
cpdef double evaluate(self, double x) except *
cdef class SinOfSquareFunction(Function):
cpdef double evaluate(self, double x) except *
from libc.math cimport sin
cdef class Function:
cpdef double evaluate(self, double x) except *:
return 0
cdef class SinOfSquareFunction(Function):
cpdef double evaluate(self, double x) except *:
return sin(x ** 2)
......@@ -32,31 +32,23 @@ function on floating point numbers:
.. literalinclude:: ../../examples/tutorial/cdef_classes/math_function_2.pyx
The directive cpdef makes two versions of the method available; one
fast for use from Cython and one slower for use from Python. Then::
fast for use from Cython and one slower for use from Python. Then:
cdef class SinOfSquareFunction(Function):
cpdef double evaluate(self, double x) except *:
return sin(x**2)
.. literalinclude:: ../../examples/tutorial/cdef_classes/sin_of_square.pyx
This does slightly more than providing a python wrapper for a cdef
method: unlike a cdef method, a cpdef method is fully overridable by
methods and instance attributes in Python subclasses. It adds a
little calling overhead compared to a cdef method.
Using this, we can now change our integration example::
To make the classes reusable across modules, we define them
in a :file:`sin_of_square.pxd` file:
def integrate(Function f, double a, double b, int N):
cdef int i
cdef double s, dx
if f is None:
raise ValueError("f cannot be None")
s = 0
dx = (b-a)/N
for i in range(N):
s += f.evaluate(a+i*dx)
return s * dx
.. literalinclude:: ../../examples/tutorial/cdef_classes/sin_of_square.pxd
print(integrate(SinOfSquareFunction(), 0, 1, 10000))
Using this, we can now change our integration example:
.. literalinclude:: ../../examples/tutorial/cdef_classes/integrate.pyx
This is almost as fast as the previous code, however it is much more flexible
as the function to integrate can be changed. We can even pass in a new
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment