apologiessirnoclue
apologiessirnoclue

Reputation: 216

Complex numbers with fractions

So I need to hold something like this:

complex(fractions.Fraction(1, 3), fractions.Fraction(1, 3))

but python is changing fraction to floating point, and since I don't want to use floating point and stay with fractions is there any other implementation of complex numbers that can do what I want? or maybe there is a possibile way to do a small change to current implementation?

Upvotes: 7

Views: 1054

Answers (1)

Lukas S
Lukas S

Reputation: 3593

You could just use sympy.

from sympy import sympify, I, re, im, expand

z = sympify(1)/3+I/3

Notice that I had to use sympify(1) since otherwise 1/3 would evaluate to a float rather than a sympy expression. Now you can do calculations with complex numbers like so

re(z) -> 1/3
im(z) -> 1/3
z*z -> (1/3+i/3)**2
expand(z*z) -> (2*i)/9

Upvotes: 4

Related Questions