Beispiel #1
0
def descr__new__(space, w_complextype, w_real, w_imag=None):
    from pypy.objspace.std.complexobject import W_ComplexObject

    # if w_real is already a complex number and there is no second
    # argument, return it.  Note that we cannot return w_real if
    # it is an instance of a *subclass* of complex, or if w_complextype
    # is itself a subclass of complex.
    noarg2 = w_imag is None
    if (noarg2 and space.is_w(w_complextype, space.w_complex)
            and space.is_w(space.type(w_real), space.w_complex)):
        return w_real

    if space.isinstance_w(w_real, space.w_str) or \
            space.isinstance_w(w_real, space.w_unicode):
        # a string argument
        if not noarg2:
            raise OperationError(
                space.w_TypeError,
                space.wrap("complex() can't take second arg"
                           " if first is a string"))
        try:
            realstr, imagstr = _split_complex(space.str_w(w_real))
        except ValueError:
            raise OperationError(space.w_ValueError, space.wrap(ERR_MALFORMED))
        try:
            realval = string_to_float(realstr)
            imagval = string_to_float(imagstr)
        except ParseStringError:
            raise OperationError(space.w_ValueError, space.wrap(ERR_MALFORMED))

    else:
        # non-string arguments
        realval, imagval = unpackcomplex(space, w_real, strict_typing=False)

        # now take w_imag into account
        if not noarg2:
            # complex(x, y) == x+y*j, even if 'y' is already a complex.
            realval2, imagval2 = unpackcomplex(space,
                                               w_imag,
                                               strict_typing=False)

            # try to preserve the signs of zeroes of realval and realval2
            if imagval2 != 0.0:
                realval -= imagval2

            if imagval != 0.0:
                imagval += realval2
            else:
                imagval = realval2
    # done
    w_obj = space.allocate_instance(W_ComplexObject, w_complextype)
    W_ComplexObject.__init__(w_obj, realval, imagval)
    return w_obj
Beispiel #2
0
def descr__new__(space, w_complextype, w_real, w_imag=None):
    from pypy.objspace.std.complexobject import W_ComplexObject

    # if w_real is already a complex number and there is no second
    # argument, return it.  Note that we cannot return w_real if
    # it is an instance of a *subclass* of complex, or if w_complextype
    # is itself a subclass of complex.
    noarg2 = w_imag is None
    if (noarg2 and space.is_w(w_complextype, space.w_complex)
               and space.is_w(space.type(w_real), space.w_complex)):
        return w_real

    if space.isinstance_w(w_real, space.w_str) or \
            space.isinstance_w(w_real, space.w_unicode):
        # a string argument
        if not noarg2:
            raise OperationError(space.w_TypeError,
                                 space.wrap("complex() can't take second arg"
                                            " if first is a string"))
        try:
            realstr, imagstr = _split_complex(space.str_w(w_real))
        except ValueError:
            raise OperationError(space.w_ValueError, space.wrap(ERR_MALFORMED))
        try:
            realval = string_to_float(realstr)
            imagval = string_to_float(imagstr)
        except ParseStringError:
            raise OperationError(space.w_ValueError, space.wrap(ERR_MALFORMED))

    else:
        # non-string arguments
        realval, imagval = unpackcomplex(space, w_real, strict_typing=False)

        # now take w_imag into account
        if not noarg2:
            # complex(x, y) == x+y*j, even if 'y' is already a complex.
            realval2, imagval2 = unpackcomplex(space, w_imag, strict_typing=False)

            # try to preserve the signs of zeroes of realval and realval2
            if imagval2 != 0.0:
                realval -= imagval2

            if imagval != 0.0:
                imagval += realval2
            else:
                imagval = realval2
    # done
    w_obj = space.allocate_instance(W_ComplexObject, w_complextype)
    W_ComplexObject.__init__(w_obj, realval, imagval)
    return w_obj
Beispiel #3
0
class TestW_ComplexObject:
    def test_instantiation(self):
        def _t_complex(r=0.0, i=0.0):
            c = W_ComplexObject(r, i)
            assert c.realval == float(r) and c.imagval == float(i)

        pairs = (
            (1, 1),
            (1.0, 2.0),
            (2L, 3L),
        )
        for r, i in pairs:
            _t_complex(r, i)

    def test_parse_complex(self):
        f = cobjtype._split_complex

        def test_cparse(cnum, realnum, imagnum):
            result = f(cnum)
            assert len(result) == 2
            r, i = result
            assert r == realnum
            assert i == imagnum

        test_cparse('3', '3', '0.0')
        test_cparse('3+3j', '3', '3')
        test_cparse('3.0+3j', '3.0', '3')
        test_cparse('3L+3j', '3L', '3')
        test_cparse('3j', '0.0', '3')
        test_cparse('.e+5', '.e+5', '0.0')
        test_cparse('(1+2j)', '1', '2')
        test_cparse('(1-6j)', '1', '-6')
        test_cparse(' ( +3.14-6J )', '+3.14', '-6')
        test_cparse(' +J', '0.0', '1.0')
        test_cparse(' -J', '0.0', '-1.0')

    def test_unpackcomplex(self):
        space = self.space
        w_z = W_ComplexObject(2.0, 3.5)
        assert space.unpackcomplex(w_z) == (2.0, 3.5)
        space.raises_w(space.w_TypeError, space.unpackcomplex, space.w_None)
        w_f = space.newfloat(42.5)
        assert space.unpackcomplex(w_f) == (42.5, 0.0)
        w_l = space.wrap(-42L)
        assert space.unpackcomplex(w_l) == (-42.0, 0.0)

    def test_pow(self):
        def _pow((r1, i1), (r2, i2)):
            w_res = W_ComplexObject(r1, i1).pow(W_ComplexObject(r2, i2))
            return w_res.realval, w_res.imagval

        assert _pow((0.0, 2.0), (0.0, 0.0)) == (1.0, 0.0)
        assert _pow((0.0, 0.0), (2.0, 0.0)) == (0.0, 0.0)
        rr, ir = _pow((0.0, 1.0), (2.0, 0.0))
        assert abs(-1.0 - rr) < EPS
        assert abs(0.0 - ir) < EPS

        def _powu((r1, i1), n):
            w_res = W_ComplexObject(r1, i1).pow_positive_int(n)
            return w_res.realval, w_res.imagval
Beispiel #4
0
    def _wrap_not_rpython(self, x):
        "NOT_RPYTHON"
        # _____ this code is here to support testing only _____

        # we might get there in non-translated versions if 'x' is
        # a long that fits the correct range.
        if is_valid_int(x):
            return self.newint(x)

        # wrap() of a container works on CPython, but the code is
        # not RPython.  Don't use -- it is kept around mostly for tests.
        # Use instead newdict(), newlist(), newtuple().
        if isinstance(x, dict):
            items_w = [(self.wrap(k), self.wrap(v))
                       for (k, v) in x.iteritems()]
            r = self.newdict()
            r.initialize_content(items_w)
            return r
        if isinstance(x, tuple):
            wrappeditems = [self.wrap(item) for item in list(x)]
            return self.newtuple(wrappeditems)
        if isinstance(x, list):
            wrappeditems = [self.wrap(item) for item in x]
            return self.newlist(wrappeditems)

        # The following cases are even stranger.
        # Really really only for tests.
        if type(x) is long:
            return self.wraplong(x)
        if isinstance(x, slice):
            return W_SliceObject(self.wrap(x.start), self.wrap(x.stop),
                                 self.wrap(x.step))
        if isinstance(x, complex):
            return W_ComplexObject(x.real, x.imag)

        if isinstance(x, set):
            res = W_SetObject(self,
                              self.newlist([self.wrap(item) for item in x]))
            return res

        if isinstance(x, frozenset):
            wrappeditems = [self.wrap(item) for item in x]
            return W_FrozensetObject(self, wrappeditems)

        if x is __builtin__.Ellipsis:
            # '__builtin__.Ellipsis' avoids confusion with special.Ellipsis
            return self.w_Ellipsis

        if self.config.objspace.nofaking:
            raise OperationError(
                self.w_RuntimeError,
                self.wrap("nofaking enabled: refusing "
                          "to wrap cpython value %r" % (x, )))
        if isinstance(x, type(Exception)) and issubclass(x, Exception):
            w_result = self.wrap_exception_cls(x)
            if w_result is not None:
                return w_result
        from pypy.objspace.std.fake import fake_object
        return fake_object(self, x)
Beispiel #5
0
 def test_unpackcomplex(self):
     space = self.space
     w_z = W_ComplexObject(2.0, 3.5)
     assert space.unpackcomplex(w_z) == (2.0, 3.5)
     space.raises_w(space.w_TypeError, space.unpackcomplex, space.w_None)
     w_f = space.newfloat(42.5)
     assert space.unpackcomplex(w_f) == (42.5, 0.0)
     w_l = space.wrap(-42L)
     assert space.unpackcomplex(w_l) == (-42.0, 0.0)
Beispiel #6
0
    def _wrap_not_rpython(self, x):
        "NOT_RPYTHON"
        # _____ this code is here to support testing only _____

        # wrap() of a container works on CPython, but the code is
        # not RPython.  Don't use -- it is kept around mostly for tests.
        # Use instead newdict(), newlist(), newtuple().
        if isinstance(x, dict):
            items_w = [(self.wrap(k), self.wrap(v))
                       for (k, v) in x.iteritems()]
            r = self.newdict()
            r.initialize_content(items_w)
            return r
        if isinstance(x, tuple):
            wrappeditems = [self.wrap(item) for item in list(x)]
            return self.newtuple(wrappeditems)
        if isinstance(x, list):
            wrappeditems = [self.wrap(item) for item in x]
            return self.newlist(wrappeditems)

        # The following cases are even stranger.
        # Really really only for tests.
        if type(x) is long:
            return self.wraplong(x)
        if isinstance(x, slice):
            return W_SliceObject(self.wrap(x.start), self.wrap(x.stop),
                                 self.wrap(x.step))
        if isinstance(x, complex):
            return W_ComplexObject(x.real, x.imag)

        if isinstance(x, set):
            res = W_SetObject(self,
                              self.newlist([self.wrap(item) for item in x]))
            return res

        if isinstance(x, frozenset):
            wrappeditems = [self.wrap(item) for item in x]
            return W_FrozensetObject(self, wrappeditems)

        if x is __builtin__.Ellipsis:
            # '__builtin__.Ellipsis' avoids confusion with special.Ellipsis
            return self.w_Ellipsis

        raise OperationError(
            self.w_RuntimeError,
            self.wrap("refusing to wrap cpython value %r" % (x, )))
Beispiel #7
0
 def newcomplex(self, realval, imagval):
     return W_ComplexObject(realval, imagval)
Beispiel #8
0
                a = space.float_w(space.getattr(w_imag, space.wrap('real')))
                b = space.float_w(space.getattr(w_imag, space.wrap('imag')))
                realval -= b
                imagval += a
            elif space.is_true(space.isinstance(w_imag, space.w_str)) or \
                     space.is_true(space.isinstance(w_imag, space.w_unicode)):
                # prevent space.float(w_imag) from succeeding
                raise OperationError(
                    space.w_TypeError,
                    space.wrap("complex() second arg"
                               " can't be a string"))
            else:
                imagval += space.float_w(space.float(w_imag))
    # done
    w_obj = space.allocate_instance(W_ComplexObject, w_complextype)
    W_ComplexObject.__init__(w_obj, realval, imagval)
    return w_obj


def complexwprop(name):
    def fget(space, w_obj):
        from pypy.objspace.std.complexobject import W_ComplexObject
        if not isinstance(w_obj, W_ComplexObject):
            raise OperationError(space.w_TypeError,
                                 space.wrap("descriptor is for 'complex'"))
        return space.newfloat(getattr(w_obj, name))

    return GetSetProperty(fget)


def descr___getnewargs__(space, w_self):
Beispiel #9
0
        assert abs(0.0 - ir) < EPS

        def _powu((r1, i1), n):
            w_res = W_ComplexObject(r1, i1).pow_positive_int(n)
            return w_res.realval, w_res.imagval
        assert _powu((0.0,2.0),0) == (1.0,0.0)
        assert _powu((0.0,0.0),2) == (0.0,0.0)
        assert _powu((0.0,1.0),2) == (-1.0,0.0)

        def _powi((r1, i1), n):
            w_res = W_ComplexObject(r1, i1).pow_small_int(n)
            return w_res.realval, w_res.imagval
        assert _powi((0.0,2.0),0) == (1.0,0.0)
        assert _powi((0.0,0.0),2) == (0.0,0.0)
        assert _powi((0.0,1.0),2) == (-1.0,0.0)
        c = W_ComplexObject(0.0,1.0)
        p = W_ComplexObject(2.0,0.0)
        r = c.descr_pow(self.space, p, self.space.wrap(None))
        assert r.realval == -1.0
        assert r.imagval == 0.0


class AppTestAppComplexTest:
    spaceconfig = {'usemodules': ['binascii', 'time', 'struct']}

    def w_check_div(self, x, y):
        """Compute complex z=x*y, and check that z/x==y and z/y==x."""
        z = x * y
        if x != 0:
            q = z / x
            assert self.close(q, y)
Beispiel #10
0
def unmarshal_Complex_bin(space, u, tc):
    real = unpack_float(u.get(8))
    imag = unpack_float(u.get(8))
    return W_ComplexObject(real, imag)
Beispiel #11
0
 def test_pow(self):
     def _pow((r1, i1), (r2, i2)):
         w_res = W_ComplexObject(r1, i1).pow(W_ComplexObject(r2, i2))
         return w_res.realval, w_res.imagval
Beispiel #12
0
 def _t_complex(r=0.0, i=0.0):
     c = W_ComplexObject(r, i)
     assert c.realval == float(r) and c.imagval == float(i)
Beispiel #13
0
        assert _pow((0.0, 2.0), (0.0, 0.0)) == (1.0, 0.0)
        assert _pow((0.0, 0.0), (2.0, 0.0)) == (0.0, 0.0)
        rr, ir = _pow((0.0, 1.0), (2.0, 0.0))
        assert abs(-1.0 - rr) < EPS
        assert abs(0.0 - ir) < EPS

        def _powu((r1, i1), n):
            w_res = W_ComplexObject(r1, i1).pow_positive_int(n)
            return w_res.realval, w_res.imagval

        assert _powu((0.0, 2.0), 0) == (1.0, 0.0)
        assert _powu((0.0, 0.0), 2) == (0.0, 0.0)
        assert _powu((0.0, 1.0), 2) == (-1.0, 0.0)

        def _powi((r1, i1), n):
            w_res = W_ComplexObject(r1, i1).pow_small_int(n)
            return w_res.realval, w_res.imagval

        assert _powi((0.0, 2.0), 0) == (1.0, 0.0)
        assert _powi((0.0, 0.0), 2) == (0.0, 0.0)
        assert _powi((0.0, 1.0), 2) == (-1.0, 0.0)
        c = W_ComplexObject(0.0, 1.0)
        p = W_ComplexObject(2.0, 0.0)
        r = pow__Complex_Complex_ANY(self.space, c, p, self.space.wrap(None))
        assert r.realval == -1.0
        assert r.imagval == 0.0


class AppTestAppComplexTest:
    def w_check_div(self, x, y):
        """Compute complex z=x*y, and check that z/x==y and z/y==x."""
Beispiel #14
0
            return w_res.realval, w_res.imagval
        assert _pow((0.0,2.0),(0.0,0.0)) == (1.0,0.0)
        assert _pow((0.0,0.0),(2.0,0.0)) == (0.0,0.0)
        rr, ir = _pow((0.0,1.0),(2.0,0.0))
        assert abs(-1.0 - rr) < EPS
        assert abs(0.0 - ir) < EPS

        def _powu((r1, i1), n):
            w_res = W_ComplexObject(r1, i1).pow_positive_int(n)
            return w_res.realval, w_res.imagval
        assert _powu((0.0,2.0),0) == (1.0,0.0)
        assert _powu((0.0,0.0),2) == (0.0,0.0)
        assert _powu((0.0,1.0),2) == (-1.0,0.0)

        def _powi((r1, i1), n):
            w_res = W_ComplexObject(r1, i1).pow_small_int(n)
            return w_res.realval, w_res.imagval
        assert _powi((0.0,2.0),0) == (1.0,0.0)
        assert _powi((0.0,0.0),2) == (0.0,0.0)
        assert _powi((0.0,1.0),2) == (-1.0,0.0)
        c = W_ComplexObject(0.0,1.0)
        p = W_ComplexObject(2.0,0.0)
        r = c.descr_pow(self.space, p, self.space.wrap(None))
        assert r.realval == -1.0
        assert r.imagval == 0.0


class AppTestAppComplexTest:
    spaceconfig = {'usemodules': ['binascii', 'time', 'struct', 'unicodedata']}

    def w_check_div(self, x, y):
                # say y == a+b*j:
                a = space.float_w(space.getattr(w_imag, space.wrap('real')))
                b = space.float_w(space.getattr(w_imag, space.wrap('imag')))
                realval -= b
                imagval += a
            elif space.is_true(space.isinstance(w_imag, space.w_str)) or \
                     space.is_true(space.isinstance(w_imag, space.w_unicode)):
                # prevent space.float(w_imag) from succeeding
                raise OperationError(space.w_TypeError,
                                     space.wrap("complex() second arg"
                                                " can't be a string"))
            else:
                imagval += space.float_w(space.float(w_imag))
    # done
    w_obj = space.allocate_instance(W_ComplexObject, w_complextype)
    W_ComplexObject.__init__(w_obj, realval, imagval)
    return w_obj

def complexwprop(name):
    def fget(space, w_obj):
        from pypy.objspace.std.complexobject import W_ComplexObject
        if not isinstance(w_obj, W_ComplexObject):
            raise OperationError(space.w_TypeError,
                                 space.wrap("descriptor is for 'complex'"))
        return space.newfloat(getattr(w_obj, name))
    return GetSetProperty(fget)
    
def descr___getnewargs__(space,  w_self):
    from pypy.objspace.std.complexobject import W_ComplexObject
    assert isinstance(w_self, W_ComplexObject)
    return space.newtuple([space.newcomplex(w_self.realval,w_self.imagval)]) 
Beispiel #16
0
    def _wrap_not_rpython(self, x):
        "NOT_RPYTHON"
        # _____ this code is here to support testing only _____

        # wrap() of a container works on CPython, but the code is
        # not RPython.  Don't use -- it is kept around mostly for tests.
        # Use instead newdict(), newlist(), newtuple().
        if isinstance(x, dict):
            items_w = [(self.wrap(k), self.wrap(v)) for (k, v) in x.iteritems()]
            r = self.newdict()
            r.initialize_content(items_w)
            return r
        if isinstance(x, tuple):
            wrappeditems = [self.wrap(item) for item in list(x)]
            return self.newtuple(wrappeditems)
        if isinstance(x, list):
            wrappeditems = [self.wrap(item) for item in x]
            return self.newlist(wrappeditems)

        # The following cases are even stranger.
        # Really really only for tests.
        if type(x) is long:
            if self.config.objspace.std.withsmalllong:
                from pypy.rlib.rarithmetic import r_longlong
                try:
                    rx = r_longlong(x)
                except OverflowError:
                    pass
                else:
                    from pypy.objspace.std.smalllongobject import \
                                                   W_SmallLongObject
                    return W_SmallLongObject(rx)
            return W_LongObject.fromlong(x)
        if isinstance(x, slice):
            return W_SliceObject(self.wrap(x.start),
                                 self.wrap(x.stop),
                                 self.wrap(x.step))
        if isinstance(x, complex):
            return W_ComplexObject(x.real, x.imag)

        if isinstance(x, set):
            rdict_w = r_dict(self.eq_w, self.hash_w)
            for item in x:
                rdict_w[self.wrap(item)] = None
            res = W_SetObject(self, rdict_w)
            return res

        if isinstance(x, frozenset):
            wrappeditems = [self.wrap(item) for item in x]
            return W_FrozensetObject(self, wrappeditems)

        if x is __builtin__.Ellipsis:
            # '__builtin__.Ellipsis' avoids confusion with special.Ellipsis
            return self.w_Ellipsis

        if self.config.objspace.nofaking:
            raise OperationError(self.w_RuntimeError,
                                 self.wrap("nofaking enabled: refusing "
                                           "to wrap cpython value %r" %(x,)))
        if isinstance(x, type(Exception)) and issubclass(x, Exception):
            w_result = self.wrap_exception_cls(x)
            if w_result is not None:
                return w_result
        from pypy.objspace.std.fake import fake_object
        return fake_object(self, x)