MCPcopy Create free account
hub / github.com/ActiveState/code / F

Class F

recipes/Python/265894_Floating_Point_Simulator/recipe-265894.py:3–35  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1prec = 8 # number of decimal digits (must be under 15)
2
3class F:
4 def __init__(self, value, full=None):
5 self.value = float('%.*e' % (prec-1, value))
6 if full is None:
7 full = self.value
8 self.full = full
9 def __str__(self):
10 return str(self.value)
11 def __repr__(self):
12 return "F(%s, %r)" % (self, self.full)
13 def error(self):
14 ulp = float('1'+('%.4e' % self.value)[-5:]) * 10 ** (1-prec)
15 return int(abs(self.value - self.full) / ulp)
16 def __coerce__(self, other):
17 if not isinstance(other, F):
18 return (self, F(other))
19 return (self, other)
20 def __add__(self, other):
21 return F(self.value + other.value, self.full + other.full)
22 def __sub__(self, other):
23 return F(self.value - other.value, self.full - other.full)
24 def __mul__(self, other):
25 return F(self.value * other.value, self.full * other.full)
26 def __div__(self, other):
27 return F(self.value / other.value, self.full / other.full)
28 def __neg__(self):
29 return F(-self.value, -self.full)
30 def __abs__(self):
31 return F(abs(self.value), abs(self.full))
32 def __pow__(self, other):
33 return F(pow(self.value, other.value), pow(self.full, other.full))
34 def __cmp__(self, other):
35 return cmp(self.value, other.value)
36
37# Example: Show failure of the associative law (Knuth Vol. 2 p.214)
38u, v, w = F(11111113), F(-11111111), F(7.51111111)

Callers 10

__coerce__Method · 0.70
__add__Method · 0.70
__sub__Method · 0.70
__mul__Method · 0.70
__div__Method · 0.70
__neg__Method · 0.70
__abs__Method · 0.70
__pow__Method · 0.70
recipe-265894.pyFile · 0.70
avgsumFunction · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected