1 | initial version |
Well after using the code a couple days, I modified it again and here is a better version. E.g. now 2+(1-sqrt(3))i is typeset as shown v.s. as 2+i+sqrt(3)i in the previous version.
<codes> def cpx(z): r""" Return a LaTeX string for this complex number. EXAMPLE:: sage: latex_of_complex(0) 0 sage: latex_of_complex(2) 2 sage: latex_of_complex(4*i) 4 \mathbf{i} sage: latex_of_complex(7 + 8*i) 7 + 8 \mathbf{i} """ if z == 0: return LatexExpr('0') re = z.real().simplify() im = z.imag().simplify() if (re == 0) or (im==0) : return LatexExpr(latex(z).replace('i',r'\mathbf{i}')) elif im > 0: s = '+' else: s = '-' rel = latex(re) iml = latex(abs(im)) if rel.find('+') >= 1 or rel.find('-') >=1: repl = r'\left('+rel+r'\right)' else: repl = rel if iml.find('+') >=1 or iml.find('-') >=1: impl = r'\left('+iml+r'\right)'+r'\mathbf{i}' else: impl = iml+r'\mathbf{i}' if abs(im) ==1: return LatexExpr(repl + s + r'\mathbf{i}') return LatexExpr(repl + s + impl) </codes>
2 | No.2 Revision |
Well after using the code a couple days, I modified it again and here is a better version. E.g. now 2+(1-sqrt(3))i is typeset as shown v.s. as 2+i+sqrt(3)i in the previous version.
<codes>def cpx(z): r""" Return a LaTeX string for this complex number. EXAMPLE:: sage: latex_of_complex(0) 0 sage: latex_of_complex(2) 2 sage: latex_of_complex(4*i) 4 \mathbf{i} sage: latex_of_complex(7 + 8*i) 7 + 8 \mathbf{i} """ if z == 0: return LatexExpr('0') re = z.real().simplify() im = z.imag().simplify() if (re == 0) or (im==0) : return LatexExpr(latex(z).replace('i',r'\mathbf{i}')) elif im > 0: s = '+' else: s = '-' rel = latex(re) iml = latex(abs(im)) if rel.find('+') >= 1 or rel.find('-') >=1: repl = r'\left('+rel+r'\right)' else: repl = rel if iml.find('+') >=1 or iml.find('-') >=1: impl = r'\left('+iml+r'\right)'+r'\mathbf{i}' else: impl = iml+r'\mathbf{i}' if abs(im) ==1: return LatexExpr(repl + s + r'\mathbf{i}') return LatexExpr(repl + s + impl)
</codes>