## With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

No credit card required

# 18.16. Simulating Floating Point

Credit: Raymond Hettinger

## Problem

You need to simulate floating-point arithmetic in software, either to show to students the details of the various classic problems with floating point (e.g., representation error, loss of precision, failure of distributive, commutative, and associative laws), or to explore the numerical robustness of alternative algorithms.

## Solution

We can reproduce every floating-point operation, with explicitly bounded precision, by coding a Python class that overloads all the special methods used in arithmetic operators:

`prec = 8 # number of decimal digits (must be under 15) class F(object): def _ _init_ _(self, value, full=None): self.value = float('%.*e' % (prec-1, value)) if full is None: full = self.value self.full = full def _ _str_ _(self): return str(self.value) def _ _repr_ _(self): return "F(%s, %r)" % (self, self.full) def error(self): ulp = float('1'+('%.4e' % self.value)[-5:]) * 10 ** (1-prec) return int(abs(self.value - self.full) / ulp) def _ _coerce_ _(self, other): if not isinstance(other, F): return (self, F(other)) return (self, other) def _ _add_ _(self, other): return F(self.value + other.value, self.full + other.full) def _ _sub_ _(self, other): return F(self.value - other.value, self.full - other.full) def _ _mul_ _(self, other): return F(self.value * other.value, self.full * other.full) def _ _div_ _(self, other): return F(self.value / other.value, self.full / other.full) def _ _neg_ _(self): return F(-self.value, ...`

## With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

No credit card required