This program (explained here) computes the volume of a piece sliced off from a cube by a plane, and also the moment of that piece about that plane. Actually it is n dimensional and takes the dimensionality from the length of the vector argument ‘a’ to routine c. The cube is actually C = [0, 1]n and the plane is the n−1 dimensional subspace {x | a∙x = 1} and the half space of interest is H = {x | a∙x < 1}. The sliced off piece is H∩C. The program works for n > 0.

We would like to locate the centroid of this piece. We take the vector notion of moment of mass distribution from here. That note also provides the formula for center of mass, or ‘centroid’. The centroid is translatable and the moments are cumulative.

The routine r returns moments 0 and 1 of the simplex that it has been assigned. The vector moment 1 is in terms of the coordinate system of the corner of the hypercube that is also a simplex vertex. The 2nd recursive call or r in r returns the 1st moment in coordinates offset by 1 in coordinate j. Routine r returns a value

Likewise routine c returns moments 0 and 1 while the test routine at the end reports centroids and compares computed moments with expected moments.

Here we add code to allow negative components. Just now (2017) I don’t remember why I wanted that.

Similar developments here