|
| 1 | +#!/usr/bin/env python |
| 2 | +# coding=utf-8 |
| 3 | + |
| 4 | +import math |
| 5 | + |
| 6 | +class Measurement: |
| 7 | + def __init__(self, val, perc): |
| 8 | + self.val = val |
| 9 | + self.perc = perc |
| 10 | + self.abs = self.val * self.perc / 100 |
| 11 | + |
| 12 | + def __repr__(self): |
| 13 | + return "Measurement({0}, {1})".format(self.val, self.perc) |
| 14 | + def __str__(self): |
| 15 | + return "{0}±{1}%".format(self.val, self.perc) |
| 16 | + |
| 17 | + def _addition_result(self, result, other_abs): |
| 18 | + new_perc = 100 * (math.hypot(self.abs, other_abs) / result) |
| 19 | + return Measurement(result, new_perc) |
| 20 | + def __add__(self, other): |
| 21 | + result = self.val + other.val |
| 22 | + return self._addition_result(result, other.abs) |
| 23 | + def __sub__(self, other): |
| 24 | + result = self.val - other.val |
| 25 | + return self._addition_result(result, other.abs) |
| 26 | + |
| 27 | + def _multiplication_result(self, result, other_perc): |
| 28 | + new_perc = math.hypot(self.perc, other_perc) |
| 29 | + return Measurement(result, new_perc) |
| 30 | + def __mul__(self, other): |
| 31 | + result = self.val * other.val |
| 32 | + return self._multiplication_result(result, other.perc) |
| 33 | + def __truediv__(self, other): |
| 34 | + result = self.val / other.val |
| 35 | + return self._multiplication_result(result, other.perc) |
| 36 | + |
| 37 | +if __name__ == "__main__": |
| 38 | + m1 = Measurement(110, 0.2) |
| 39 | + m2 = Measurement(134, 0.1) |
| 40 | + print("m1:{0}".format(m1)) |
| 41 | + print("m2:{0}".format(m2)) |
| 42 | + print("m1+m2={0}".format(m1+m2)) |
| 43 | + print("m1-m2={0}".format(m1-m2)) |
| 44 | + print("m1*m2={0}".format(m1*m2)) |
| 45 | + print("m1/m2={0}".format(m1/m2)) |
0 commit comments