A very basic class for numeric values with measuring error. It only supports summation and multiplication for values under certain conditions, such as independent and homoscedastic measuring errors – hence, the actual use of the class in this state is very limited, with lots of room for improvement.
Assuming two values $x_1,x_2$ with absolute measuring errors $\epsilon_1,\epsilon_2$, the measuring error of the sum ($\epsilon_s$) and the product ($\epsilon_p$) can be approximated with the formulas
$$\epsilon_s=\sqrt{\epsilon_1^2+\epsilon_2^2}$$
and
$$\epsilon_p=\left(x_1\cdot x_2\right)\sqrt{\left(\frac{\epsilon_1}{x_1}\right)^2+\left(\frac{\epsilon_2}{x_2}\right)^2}.$$
The value $\epsilon_1/x_1$ is also called relative measuring error.
Note that the formulas remain the same for subtraction and division. Download(zip).
//Knowledgedump.org - Implementation of a class containing a numeric value with measuring error. #ifndef MEASURING_ERROR_H //Include guard #define MEASURING_ERROR_H #include <iostream> #include <cmath> //For sqrt and pow functions. class ErrVal { public: ErrVal(double value, double error); //Constructor with value and (absolute) measuring error. double value() const; //Returns element value. double abs_err() const; //Returns absolute error. double rel_err() const; //Returns relative error err/val. ErrVal operator+(const ErrVal& ev); //Summation of two values with measuring error. ErrVal operator*(const ErrVal& ev); private: double val; //Numeric value as double. double err; //Absolute measuring error. }; //Constructor ErrVal::ErrVal(double value, double error) { val = value; err = error; } //Return value double ErrVal::value() const { return val; } //Return absolute measuring error double ErrVal::abs_err() const { return err; } //Return relative measuring error double ErrVal::rel_err() const { return err / val; } //Summation of two values with measuring error ErrVal ErrVal::operator+(const ErrVal& ev) { ErrVal out(0, 0); out.val = val + ev.val; out.err = std::sqrt(std::pow(abs_err(), 2.0) + std::pow(ev.abs_err(), 2.0)); return out; } //Product of two values with measuring error ErrVal ErrVal::operator*(const ErrVal& ev) { ErrVal out(0, 0); out.val = val * ev.val; out.err = std::sqrt(std::pow(rel_err(), 2.0) + std::pow(ev.rel_err(), 2.0)) * out.val; return out; } #endif //Include guard
//Knowledgedump.org - Example file. #include "measuring_error.h" int main() { ErrVal a(100.0, 2.0), b(50.0, 10.0); //Calculate value, absolute and relative error for the sum. ErrVal s = a + b; std::cout << s.value() << " +- " << s.abs_err() << " (" << s.rel_err() * 100 << " %)" << std::endl; //Value, absolute and relative error of the product. ErrVal p = a * b; std::cout << p.value() << " +- " << p.abs_err() << " (" << p.rel_err() * 100 << " %)" << std::endl; return 0; }
150 +- 10.198 (6.79869 %) 5000 +- 1004.99 (20.0998 %)