Last active
December 25, 2015 12:39
-
-
Save apalala/6978063 to your computer and use it in GitHub Desktop.
Python xfloat with division by zero returning inf.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
This is a partial solution because several other operator methods | |
should be overridden for absolute consistency. | |
The complete list is at: | |
http://docs.python.org/2/reference/datamodel.html#emulating-numeric-types | |
http://docs.python.org/3/reference/datamodel.html#emulating-numeric-types | |
''' | |
import math | |
class xfloat(float): | |
def __add__(self, n): | |
return xfloat(super(xfloat, self).__add__(n)) | |
def __sub__(self, n): | |
return xfloat(super(xfloat, self).__sub__(n)) | |
def __mul__(self, n): | |
return xfloat(super(xfloat, self).__mul__(n)) | |
def __div__(self, d): | |
try: | |
return xfloat(super(xfloat, self).__div__(d)) | |
except ZeroDivisionError: | |
return self * float('inf') | |
def main(): | |
a = xfloat(-math.pi) | |
print a / 1.0 | |
print a / 0.0 | |
b = a * 2 | |
print b | |
print b / 0.0 | |
c = float(b) | |
print c / 0.0 | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment