
P1: JYS
c03 JWBK378-Fletcher May 1, 2009 19:52 Printer: Yet to come
24 Financial Modelling in Python
Sum the Elements of an Array
The first example simply sums the elements of the incoming array.
double sum array(PyObject* input)
{
boost::shared
ptr<PyArrayObject> obj = ::ppf::util::python
::detail::object
as array(input, PyArray DOUBLE, 0, 0);
// compute size of array
int n = 1;
if(obj->nd > 0)
for(int i = 0; i < obj->nd; ++i)
n *= obj->dimensions[i];
double* array = reinterpret
cast<double*>(obj->data);
return std::accumulate(array, array + n, 0.);
}
In Python:
>>> import numpy
>>> from ppf.math.numpy
examples import *
>>> a = numpy.array([1., 2., 3., 4.])
>>> print sum
array(a)
10.0
Compute the Trace of an Array
The next function computes the trace of a two-dimensional array sum (of the main diagonal
elements).
double trace(PyObject* input)
{
boost::shared
ptr<PyArrayObject> obj = ::ppf::util::python
::detail::object
as array(input, PyArray DOUBLE, 2, 2);
int n = obj->dimensions[0];
if(n > obj->dimensions[1]) n = obj->dimensions[1];
double sum = 0.;
for(int i = 0; i < n; ++i)
sum += *reinterpret
cast<double*>(
obj->data + i*obj->strides[0] + i*obj->strides[1]);
return sum;
}
Continuing the above example interpreter session:
>>> a = numpy.zeros((3, 4))
>>> for i in range(3):