C++: Pythagorean Means

Bjarne-stroustrup
 

Compute all three of the Pythagorean means of the set of integers 1 through 10.

Show that A(x_1,\ldots,x_n) \geq G(x_1,\ldots,x_n) \geq H(x_1,\ldots,x_n) for this set of positive integers.

  • The most common of the three means, the arithmetic mean, is the sum of the list divided by its length:
 A(x_1, \ldots, x_n) = \frac{x_1 + \cdots + x_n}{n}
 G(x_1, \ldots, x_n) = \sqrt[n]{x_1 \cdots x_n}
  • The harmonic mean is n divided by the sum of the reciprocal of each item in the list:
 H(x_1, \ldots, x_n) = \frac{n}{\frac{1}{x_1} + \cdots + \frac{1}{x_n}}

#include <vector>
#include <iostream>
#include <numeric>
#include <cmath>
#include <algorithm>

double toInverse ( int i ) {
	return  1.0 / i  ;
}

int main( ) {
	std::vector<int> numbers ;
	for ( int i = 1 ; i < 11 ; i++ ) 
	numbers.push_back( i ) ;
	double arithmetic_mean = std::accumulate( numbers.begin( ) , numbers.end( ) , 0 ) / 10.0 ;
	double geometric_mean =
	pow( std::accumulate( numbers.begin( ) , numbers.end( ) , 1 , std::multiplies<int>( ) ), 0.1 ) ;
	std::vector<double> inverses ;
	inverses.resize( numbers.size( ) ) ;
	std::transform( numbers.begin( ) , numbers.end( ) , inverses.begin( ) , toInverse ) ;  
	double harmonic_mean = 10 / std::accumulate( inverses.begin( ) , inverses.end( ) , 0.0 ); //initial value of accumulate must be a double!
	std::cout << "The arithmetic mean is " << arithmetic_mean << " , the geometric mean " 
	<< geometric_mean << " and the harmonic mean " << harmonic_mean << " !\n" ;
	return 0 ;
}
Output:
The arithmetic mean is 5.5 , the geometric mean 4.52873 and the harmonic mean 3.41417 !

SOURCE

Content is available under GNU Free Documentation License 1.2