ich les grad ein Beispiel über Klassen (s.u.).
Der Code erzeugt bei mir folgenden Error:
TypeError: unsupported operand type(s) for /: 'IntervalMath' and 'IntervalMath'
Ich kapier nicht, warum die Divison nicht funktioniert, die anderen Operationen aber anstandslos durchlaufen...
Code: Alles auswählen
class IntervalMath:
def __init__(self, lower, upper):
self.lo = float(lower)
self.up = float(upper)
def __add__(self, other):
a, b, c, d = self.lo, self.up, other.lo, other.up
return IntervalMath(a + c, b + d)
def __sub__(self, other):
a, b, c, d = self.lo, self.up, other.lo, other.up
return IntervalMath(a - d, b - c)
def __mul__(self, other):
a, b, c, d = self.lo, self.up, other.lo, other.up
return IntervalMath(min(a*c, a*d, b*c, b*d), max(a*c, a*d, b*c, b*d))
def __div__(self, other):
a, b, c, d = self.lo, self.up, other.lo, other.up
# [c, d] cannot contain zero:
if c*d <= 0:
raise ValueError\
(f'Interval {other} cannot be denominator because it contains zero')
return IntervalMath(min(a/c, a/d, b/c, b/d), max(a/c, a/d, b/c, b/d))
def __str__(self):
return f'[{self.lo:g}, {self.up:g}]'
if __name__ == '__main__':
I = IntervalMath
a = I(-3, -2)
b = I(4, 5)
expr = 'a+b', 'a-b', 'a*b', 'a/b'
for e in expr:
print(f'{e} =', eval(e))