Example #1
0
 def __init__(self, real, imag=None):
     def find_prec(s):
         if isinstance(s, string_types):
             # strip negatives and exponent
             s = s.replace("-","")
             if "e" in s:
                 s = s[:s.find("e")]
             return ceil(len(s) * 3.322)
         else:
             try:
                 return s.parent().precision()
             except Exception:
                 return 53
     if imag is None:
         # Process strings
         if isinstance(real, string_types):
             M = CC_RE.match(real)
             if M is None:
                 raise ValueError("'%s' not a valid complex number" % real)
             a, b = M.groups()
             # handle missing coefficient of i
             if b == '-':
                 b = '-1'
             elif b in ['+', '']:
                 b = '1'
             # The following is a good guess for the bit-precision,
             # but we use LmfdbRealLiterals to ensure that our number
             # prints the same as we got it.
             prec = max(find_prec(a), find_prec(b), 53)
             parent = ComplexField(prec)
             R = parent._real_field()
             self._real_literal = LmfdbRealLiteral(R, a)
             self._imag_literal = LmfdbRealLiteral(R, b)
         elif isinstance(real, LmfdbRealLiteral):
             parent = ComplexField(real.parent().precision())
             self._real_literal = real
             self._imag_literal = parent._real_field()(0)
         elif isintance(real, ComplexLiteral):
             parent = real.parent()
             self._real_literal = real._real_literal
             self._imag_literal = real._imag_literal
         else:
             raise TypeError("Object '%s' of type %s not valid input" % (real, type(real)))
     else:
         prec = max(find_prec(real), find_prec(imag), 53)
         R = RealField(prec)
         parent = ComplexField(prec)
         for x, xname in [(real, '_real_literal'), (imag, '_imag_literal')]:
             if isinstance(x, string_types):
                 x = LmfdbRealLiteral(R, x)
             if not isinstance(x, LmfdbRealLiteral):
                 raise TypeError("Object '%s' of type %s not valid input" % (x, type(x)))
             setattr(self, xname, x)
     ComplexNumber.__init__(self, self.real(), self.imag())