Example #1
0
  private static PyObject _divmod(PyComplex value, PyComplex right) {
    Py.warning(Py.DeprecationWarning, "complex divmod(), // and % are deprecated");
    PyComplex z = (PyComplex) _div(value, right);

    z.real = Math.floor(z.real);
    z.imag = 0.0;

    return new PyTuple(z, value.__sub__(z.__mul__(right)));
  }
Example #2
0
  @ExposedNew
  public static PyObject complex_new(
      PyNewWrapper new_, boolean init, PyType subtype, PyObject[] args, String[] keywords) {
    ArgParser ap = new ArgParser("complex", args, keywords, "real", "imag");
    PyObject real = ap.getPyObject(0, Py.Zero);
    PyObject imag = ap.getPyObject(1, null);

    // Special-case for single argument that is already complex
    if (real.getType() == TYPE && new_.for_type == subtype && imag == null) {
      return real;
    }
    if (real instanceof PyString) {
      if (imag != null) {
        throw Py.TypeError("complex() can't take second arg if first is a string");
      }
      return real.__complex__();
    }
    if (imag != null && imag instanceof PyString) {
      throw Py.TypeError("complex() second arg can't be a string");
    }

    try {
      real = real.__complex__();
    } catch (PyException pye) {
      if (!Py.matchException(pye, Py.AttributeError)) {
        // __complex__ not supported
        throw pye;
      }
      // otherwise try other means
    }

    PyComplex complexReal;
    PyComplex complexImag;
    PyFloat toFloat = null;
    if (real instanceof PyComplex) {
      complexReal = (PyComplex) real;
    } else {
      try {
        toFloat = real.__float__();
      } catch (PyException pye) {
        if (Py.matchException(pye, Py.AttributeError)) {
          // __float__ not supported
          throw Py.TypeError("complex() argument must be a string or a number");
        }
        throw pye;
      }
      complexReal = new PyComplex(toFloat.getValue());
    }

    if (imag == null) {
      complexImag = new PyComplex(0.0);
    } else if (imag instanceof PyComplex) {
      complexImag = (PyComplex) imag;
    } else {
      toFloat = null;
      try {
        toFloat = imag.__float__();
      } catch (PyException pye) {
        if (Py.matchException(pye, Py.AttributeError)) {
          // __float__ not supported
          throw Py.TypeError("complex() argument must be a string or a number");
        }
        throw pye;
      }
      complexImag = new PyComplex(toFloat.getValue());
    }

    complexReal.real -= complexImag.imag;
    complexReal.imag += complexImag.real;
    if (new_.for_type != subtype) {
      complexReal = new PyComplexDerived(subtype, complexReal.real, complexReal.imag);
    }
    return complexReal;
  }