Complex numbers can be thought of as polynomials
of degree at most one in i
.
To print polynomial expressions in some quantity,
two common choices are to order by increasing
or by decreasing powers of that quantity.
The choice made in Sage is usually by decreasing powers,
which is at odds with the usage of writing complex numbers
with real component first and imaginary component second.
Power series are another family of structures whose elements
involve combinations of powers of a variable, but which, in Sage,
are printed by ascending powers of the variables.
Here is a little function for printing complex numbers in our
usual order, taking advantage of that.
def cprint(z):
r"""
Print this complex number as `a + b*i` instead of `b*I + a`.
EXAMPLES:
sage: aa = [2 + 3*i, -1/2 + sqrt(3)/2*i, (1+sqrt(5))/2 + (1+sqrt(5))/2*i]
sage: for a in aa:
....: cprint(a)
"""
v = vector([z.real(), z.imag()])
R = v.base_ring()
print(R[['i']](v.list()))
(It would be easy to tweak to return a string instead of printing it,
and to optionally provide a LaTeX form.)
Examples:
sage: u = 2 + 3*i
sage: print(u); cprint(u)
3*I + 2
2 + 3*i
sage: v = -1/2 + sqrt(3)/2*i
sage: print(v); cprint(v)
1/2*I*sqrt(3) - 1/2
-1/2 + 1/2*sqrt(3)*i
sage: w = (1+sqrt(5))/2 + (1+sqrt(5))/2*i
sage: print(w); cprint(w)
(1/2*I + 1/2)*sqrt(5) + 1/2*I + 1/2
1/2*sqrt(5) + 1/2 + (1/2*sqrt(5) + 1/2)*i
Welcome to Ask Sage!
Thank you for your question!
Typing [ imaginary part ] in Ask Sage's "search or ask your question" box reveals a similar question:
Things have changed in Sage since two years ago though, and nowadays inputting
2 + 3*I
gives an element inQQ[i]
rather than in the symbolic ring, so the discussion at Ask Sage question 44894 is somewhat obsolete, and it's good you asked again.@
slelievre
: Would you care to explain :Also:
This might deserve some documentation, possibly in the tutorials...
@Emmanuel Charpentier -- slightly off topic here (could be a separate Ask Sage question) but here we go.
The result of multiplying by
x
lives in the symbolic ring. The symbolic ring wraps its constants. Compare:This allows to write equations such as