Class 2/2
By default, C++ makes all class variables and functions private. That means you can actually declare private variables and functions at the top of your class declaration without even labeling them private:
main.cpp
#include <iostream>
#include "gaussian.h"
int main ()
{
Gaussian mygaussian(30.0,20.0);
Gaussian othergaussian(10.0,30.0);
std::cout << "average " << mygaussian.mu << std::endl;
std::cout << "evaluation " << mygaussian.evaluate(15.0) << std::endl;
std::cout << "mul results sigma " << mygaussian.mul(othergaussian).sigma2 << std::endl;
std::cout << "mul results average " << mygaussian.mul(othergaussian).mu << std::endl;
std::cout << "add results sigma " << mygaussian.add(othergaussian).sigma2 << std::endl;
std::cout << "add results average " << mygaussian.add(othergaussian).mu << std::endl;
std::cout << "average " << mygaussian.mu << std::endl;
mygaussian.mu = 25;
std::cout << "average " << mygaussian.mu << std::endl;
return 0;
}
gausian.cpp
#include <math.h> /* sqrt, exp */
#include "gaussian.h"
Gaussian::Gaussian() {
mu = 0;
sigma2 = 1;
}
Gaussian::Gaussian (float average, float sigma) {
mu = average;
sigma2 = sigma;
}
float Gaussian::evaluate(float x) {
float coefficient;
float exponential;
coefficient = 1.0 / sqrt (2.0 * M_PI * sigma2);
exponential = exp ( pow (-0.5 * (x - mu), 2) / sigma2 );
return coefficient * exponential;
}
Gaussian Gaussian::mul(Gaussian other) {
float denominator;
float numerator;
float new_mu;
float new_var;
denominator = sigma2 + other.sigma2;
numerator = mu * other.sigma2 + other.mu * sigma2;
new_mu = numerator / denominator;
new_var = 1.0 / ( (1.0 / sigma2) + (1.0 / other.sigma2) );
return Gaussian(new_mu, new_var);
}
Gaussian Gaussian::add(Gaussian other) {
float new_mu;
float new_sigma2;
new_mu = mu + other.mu;
new_sigma2 = sigma2 + other.sigma2;
return Gaussian(new_mu, new_sigma2);
}
gaussian.h
Instead of writing the entire declaration twice, a better option is to put the declaration into a header file. Then you can include the entire declaration with a single line of code:
class Gaussian
{
public:
float mu, sigma2;
// constructor functions
Gaussian ();
Gaussian (float, float);
// functions to evaluate
float evaluate (float);
Gaussian mul (Gaussian);
Gaussian add (Gaussian);
};
Last updated
Was this helpful?