It seems that the already mentioned SymPy would be the most suitable way - how you can do what you need and not do require your software to be written in a special language, for example, on the mentioned mathematical products.
On the other hand, if you donβt want to introduce additional dependencies, and your irrational cases are limited to multiplying square roots, this is not an easy task in Python:
class Irrational(float): def __new__(cls, base, radix=1): self = float.__new__(cls, base ** (1.0/radix)) self.base = base self.radix = radix return self def __mul__(self, other): if isinstance(other, Irrational) and other.radix == self.radix: return Irrational(self.base * other.base, self.radix) return float.__mul__(self, other)
Example:
>>> a = Irrational(5,2) >>> a 2.2360679774997898 >>> a * Irrational(5,2) 5.0
You can continue it and include ohter operations and corner cases. But for compes expressions, you'll soon realize that you still have to use symbolic math.
jsbueno
source share