map reduce for functioneren with two parameters

H. S. Teoh via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Aug 6 11:56:18 PDT 2014


On Wed, Aug 06, 2014 at 06:44:44PM +0000, Martijn Pot via Digitalmars-d-learn wrote:
> I was wondering whether there is a way to use map reduce to calculate
> e.g.  the weighted mean and weighted standard deviation. These would
> not only need the values, but also the weights.

You can probably do this if each element of the range contains the
weight. If it isn't already part of your structure, you can use zip to
associate them together. Perhaps something like this:

	// Warning: untested code
	float[] values = ...;
	float[] weights = ...;

	assert(values.length == weights.length);

	auto weightedMean = reduce!(
			// b[0] == values[i]; b[1] == weights[i]
			(a,b) => a + b[0]*b[1]
		)(zip(values,weights)) / values.length;

Of course, values and weights don't have to be arrays, zip works with
arbitrary ranges.


T

-- 
People tell me that I'm skeptical, but I don't believe it.


More information about the Digitalmars-d-learn mailing list