Python has a built-in module that supports exact calculations with rational numbers:

from fractions import Fraction print(Fraction(2, 3) + Fraction(5, 7)) 

Everything is great, considering that by default python uses long arithmetic.

I recently needed to use complex numbers only with rational imaginary and real parts. Here's what came of it:

 >>> from fractions import Fraction >>> print(Fraction(2, 3) + Fraction(5, 7) * 1j) (0.6666666666666666+0.7142857142857143j) >>> print(complex(Fraction(2, 3), Fraction(5, 7))) (0.6666666666666666+0.7142857142857143j) 

Fraction automatically cast to float . How to solve a problem?

In C ++, for example, one could do this:

 complex<Fraction> z(Fraction(2, 3), Fraction(5, 7)); 

Could something like this be done in Python?

So far, I see only one solution to write my own Complex class, but I hope there is a simpler solution.

    1 answer 1

    I'm afraid there is really no other way.

    The only thing that, in a good form, will be inherited from the abstract class Complex https://docs.python.org/3.5/library/numbers.html . This will prevent any important methods from being missed and will eventually make the class with the interface identical to the original one.