[ create a new paste ] login | about

Link: http://codepad.org/J9oJ1Pbm    [ raw code | output | fork ]

C++, pasted on Oct 21:
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <numeric>
//	* @brief 平均値
//	* @param[in] Iterator first	配列の先頭
//	* @param[in] Iterator last   配列の末尾
//	* @return sum / cou		平均値
template<class ResultType>
typename std::iterator_traits<ResultType>::value_type average(ResultType first, ResultType last)
{
	typedef typename std::iterator_traits<ResultType>::value_type value_type;
	size_t cou = distance( last, first );
	value_type sum = std::accumulate(first, last, value_type(0.0));
	return sum / cou;
}

template <typename ResultType>
class StandardDeviation
{
	//	/** @brief コンテナの要素値
	ResultType val_;
public:
	//	/**	@brief コンストラクタ
	StandardDeviation( const ResultType& val ) : val_( val ){}
	//	* @brief 平方和を取得
	//	* @param[in] 要素 
	void operator()( ResultType& elem ) const
	{
		elem -= val_;
		elem *= elem;
	}
};

using namespace std;

int main()
{
	vector<double> vec;

	vec.push_back(10.0);
	vec.push_back(20.0);
	vec.push_back(30.0);
	vec.push_back(40.0);
	vec.push_back(50.0);

	double AVE = 0.0;
	double D = 0.0;
	double SD = 0.0;

	AVE = average(vec.begin(), vec.end());
	cout << "平均は " << AVE << "\n";

	for_each( vec.begin(), vec.end(), StandardDeviation<double>( AVE ) );
	copy(vec.begin(), vec.end(), ostream_iterator<double>(cout, "\n"));

	D = std::accumulate(vec.begin(), vec.end(), 0.0) / vec.size();
	cout << "分散は  " << D << "\n";

	SD = sqrt(D);
	cout << SD  << "\n";

	return 0;
}


Output:
1
2
3
4
5
6
7
8
平均は 3.49246e-08
100
400
900
1600
2500
分散は  1100
33.1662


Create a new paste based on this one


Comments: