May-07-2019, 09:33 PM
this changed version of my previous code should be able to sum, subtract and multiply
an interval with an integer or float, and the result should be given by integers/floats
respectively.
for instance
1 + interval(2,3) should give [3,4]
but
1.0 + interval(2,3) should give [3.0, 4.0]
I thought that for addition, I had to use __radd__ and I am not sure if I am right.
This is the code:
an interval with an integer or float, and the result should be given by integers/floats
respectively.
for instance
1 + interval(2,3) should give [3,4]
but
1.0 + interval(2,3) should give [3.0, 4.0]
I thought that for addition, I had to use __radd__ and I am not sure if I am right.
This is the code:
class interval: def __init__(self,left,right): self.right=right self.left=left def __radd__(self,other): a,b = self.left + other, self.right + other return interval(a+b) def __sub__(self,other): a,b,c,d=self.left,self.right,other.left,other.right return interval(min(a,b)-max(c,d),max(a,b)-min(c,d)) def __mul__(self,other): a,b,c,d=self.left,self.right,other.left,other.right return interval(min(a*c, a*d, b*c, b*d), max(a*c, a*d, b*c, b*d)) def __truediv__(self, other): a, b, c, d = self.left, self.right, other.left, other.right # [c,d] cannot contain zero: print(min(a/c, a/d, b/c, b/d)) if c*d <= 0: raise ValueError ('Interval %s cannot be denominator because it contains zero' % other) return interval(min(a/c, a/d, b/c, b/d), max(a/c, a/d, b/c, b/d)) def __contains__(self,other): return (other>=self.left and other<=self.right) def __repr__(self): return '[{},{}]'.format(self.left,self.right) print(interval(1,2) + 1)and this is the error I get:
Error: File "<ipython-input-838-717f169c285d>", line 1, in <module>
runfile('C:/Users/Desktop/python ode/extrial.py', wdir='C:/Users/Desktop/python ode')
File "C:\Users\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 668, in runfile
execfile(filename, namespace)
File "C:\Users\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 108, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/Desktop/python ode/extrial.py", line 221, in <module>
print(interval(1,2) + 1)
TypeError: unsupported operand type(s) for +: 'interval' and 'int'