Debian Codegraph @

pypy/objspace/std/complexobject.py

raw symbols SCIP
1 import math
2
3 from rpython.rlib import jit, rcomplex
4 from rpython.rlib.rarithmetic import intmask, r_ulonglong
5 from rpython.rlib.rbigint import rbigint
6 from rpython.rlib.rfloat import (
7 DTSF_STR_PRECISION, formatd, string_to_float)
8 from rpython.rlib.special_value import NAN
9 from rpython.rlib.rstring import ParseStringError
10 from rpython.rlib import objectmodel
11
12 from pypy.interpreter.baseobjspace import W_Root
13 from pypy.interpreter.error import OperationError, oefmt
14 from pypy.interpreter.gateway import WrappedDefault, interp2app, unwrap_spec
15 from pypy.interpreter.typedef import GetSetProperty, TypeDef, default_identity_hash
16 from pypy.objspace.std import newformat
17 from pypy.objspace.std.floatobject import _hash_float, _remove_underscores
18 from pypy.objspace.std.unicodeobject import unicode_to_decimal_w
19
20 HASH_IMAG = 1000003
21
22
23 def _split_complex(s):
24 def iswhitespace(ch):
25 return (ch == ' ' or ch == '\f' or ch == '\n' or ch == '\r' or
26 ch == '\t' or ch == '\v')
27 slen = len(s)
28 if slen == 0:
29 raise ValueError
30 realstart = 0
31 realstop = 0
32 imagstart = 0
33 imagstop = 0
34 imagsign = ' '
35 i = 0
36 # ignore whitespace at beginning and end
37 while i < slen and iswhitespace(s[i]):
38 i += 1
39 while slen > 0 and iswhitespace(s[slen-1]):
40 slen -= 1
41
42 if s[i] == '(' and s[slen-1] == ')':
43 i += 1
44 slen -= 1
45 # ignore whitespace after bracket
46 while i < slen and s[i] == ' ':
47 i += 1
48 while slen > 0 and s[slen-1] == ' ':
49 slen -= 1
50
51 # extract first number
52 realstart = i
53 pc = s[i]
54 while i < slen and s[i] != ' ':
55 if s[i] in ('+', '-') and pc not in ('e', 'E') and i != realstart:
56 break
57 pc = s[i]
58 i += 1
59
60 realstop = i
61
62 # return appropriate strings if only one number is there
63 if i >= slen:
64 newstop = realstop - 1
65 if newstop < 0:
66 raise ValueError
67 if s[newstop] in ('j', 'J'):
68 if realstart == newstop:
69 imagpart = '1.0'
70 elif realstart == newstop-1 and s[realstart] == '+':
71 imagpart = '1.0'
72 elif realstart == newstop-1 and s[realstart] == '-':
73 imagpart = '-1.0'
74 else:
75 imagpart = s[realstart:newstop]
76 return '0.0', imagpart
77 else:
78 return s[realstart:realstop], '0.0'
79
80 # find sign for imaginary part
81 if s[i] == '-' or s[i] == '+':
82 imagsign = s[i]
83 else:
84 raise ValueError
85
86 i += 1
87 if i >= slen:
88 raise ValueError
89
90 imagstart = i
91 pc = s[i]
92 while i < slen and s[i] != ' ':
93 if s[i] in ('+', '-') and pc not in ('e', 'E'):
94 break
95 pc = s[i]
96 i += 1
97
98 imagstop = i - 1
99 if imagstop < 0:
100 raise ValueError
101 if s[imagstop] not in ('j', 'J'):
102 raise ValueError
103 if imagstop < imagstart:
104 raise ValueError
105
106 if i < slen:
107 raise ValueError
108
109 realpart = s[realstart:realstop]
110 if imagstart == imagstop:
111 imagpart = '1.0'
112 else:
113 imagpart = s[imagstart:imagstop]
114 if imagsign == '-':
115 imagpart = imagsign + imagpart
116
117 return realpart, imagpart
118
119
120 def format_float(x, code, precision):
121 # like float2string, except that the ".0" is not necessary
122 if math.isinf(x):
123 if x > 0.0:
124 return "inf"
125 else:
126 return "-inf"
127 elif math.isnan(x):
128 return "nan"
129 else:
130 return formatd(x, code, precision)
131
132 def repr_format(x):
133 return format_float(x, 'r', 0)
134
135
136 def unpackcomplex(space, w_complex, allow_subclass=False, firstarg=True):
137 """
138 convert w_complex into a complex and return the unwrapped (real, imag)
139 tuple. If allow_subclass (i.e. _PyComplex_AsCComplex) we fast path subclasses
140 of complex.
141 """
142 if type(w_complex) is W_ComplexObject:
143 return (w_complex.realval, w_complex.imagval)
144 if allow_subclass and isinstance(w_complex, W_ComplexObject):
145 return (w_complex.realval, w_complex.imagval)
146 #
147 # test for a '__complex__' method, and call it if found.
148 w_z = None
149 w_method = space.lookup(w_complex, '__complex__')
150 if w_method is not None:
151 w_z = space.get_and_call_function(w_method, w_complex)
152 #
153 if w_z is not None:
154 # __complex__() must return a complex
155 if isinstance(w_z, W_ComplexObject):
156 if type(w_z) is not W_ComplexObject:
157 space.warn(
158 space.newtext("__complex__ returned non-complex (type %s). The ability to return an instance of a strict subclass of complex is deprecated, and may be removed in a future version of Python." % (space.type(w_z).getname(space))),
159 space.w_DeprecationWarning
160 )
161 return (w_z.realval, w_z.imagval)
162 raise oefmt(space.w_TypeError,
163 "__complex__() must return a complex number")
164
165 # try to see whether it has an __index__
166 if space.lookup(w_complex, '__index__') is not None:
167 result = space.float_w(space.float(space.index(w_complex)))
168 return (result, 0.0)
169
170 #
171 # no '__complex__' method, so we assume it is a float,
172 # unless it is an instance of some subclass of complex.
173 if space.isinstance_w(w_complex, space.gettypefor(W_ComplexObject)):
174 real = space.float(space.getattr(w_complex, space.newtext("real")))
175 imag = space.float(space.getattr(w_complex, space.newtext("imag")))
176 return (space.float_w(real), space.float_w(imag))
177 #
178 # Check that it is not a string (on which space.float() would succeed).
179 if (space.isinstance_w(w_complex, space.w_bytes) or
180 space.isinstance_w(w_complex, space.w_unicode)):
181 raise oefmt(space.w_TypeError,
182 "complex number expected, got '%T'", w_complex)
183 #
184 try:
185 return (space.float_w(space.float(w_complex)), 0.0)
186 except OperationError as e:
187 if not e.match(space, space.w_TypeError):
188 raise
189 if firstarg:
190 raise oefmt(space.w_TypeError,
191 "complex() first argument must be a string or a number, not '%T'",
192 w_complex)
193 else:
194 raise oefmt(space.w_TypeError,
195 "complex() second argument must be a number, not '%T'",
196 w_complex)
197
198 # Python3 semantics of c_pow have changed slightly
199
200 def c_pow(x, y):
201 (a_r, a_i), (b_r, b_i) = x, y
202 if b_r == 0 and b_i == 0:
203 rr, ir = (1., 0.)
204 elif (a_r == 0. or math.isinf(a_r)) and a_i == 0:
205 if b_i != 0. or b_r < 0:
206 raise ZeroDivisionError
207 rr, ir = (0.0, 0.0)
208 else:
209 vabs = math.hypot(a_r, a_i)
210 len = math.pow(vabs, b_r)
211 at = math.atan2(a_i, a_r)
212 phase = at * b_r
213 if b_i != 0.0:
214 len /= math.exp(at * b_i)
215 phase += b_i * math.log(vabs)
216 try:
217 rr = len * math.cos(phase)
218 ir = len * math.sin(phase)
219 except ValueError:
220 rr = NAN
221 ir = NAN
222 return (rr, ir)
223
224
225 class W_ComplexObject(W_Root):
226 _immutable_fields_ = ['realval', 'imagval']
227
228 def __init__(self, realval=0.0, imgval=0.0):
229 self.realval = float(realval)
230 self.imagval = float(imgval)
231
232 def unwrap(self, space): # for tests only
233 return complex(self.realval, self.imagval)
234
235 def __repr__(self):
236 """ representation for debugging purposes """
237 return "<W_ComplexObject(%f, %f)>" % (self.realval, self.imagval)
238
239 def as_tuple(self):
240 return (self.realval, self.imagval)
241
242 def sub(self, other):
243 return W_ComplexObject(self.realval - other.realval,
244 self.imagval - other.imagval)
245
246 @objectmodel.always_inline
247 def mul(self, other):
248 r, i = self.mul_components(self.realval, self.imagval, other.realval, other.imagval)
249 return W_ComplexObject(r, i)
250
251 @staticmethod
252 @objectmodel.always_inline
253 def mul_components(self_real, self_imag, other_real, other_imag):
254 r = self_real * other_real - self_imag * other_imag
255 i = self_real * other_imag + self_imag * other_real
256 return r, i
257
258 def div(self, other):
259 rr, ir = rcomplex.c_div(self.as_tuple(), other.as_tuple())
260 return W_ComplexObject(rr, ir)
261
262 def pow(self, other):
263 rr, ir = c_pow(self.as_tuple(), other.as_tuple())
264 return W_ComplexObject(rr, ir)
265
266 def pow_small_int(self, n):
267 if n >= 0:
268 if jit.isconstant(n) and n == 2:
269 return self.mul(self)
270 return self.pow_positive_int(self.realval, self.imagval, n)
271 else:
272 return w_one.div(self.pow_positive_int(self.realval, self.imagval, -n))
273
274 @staticmethod
275 def pow_positive_int(self_real, self_imag, n):
276 mask = 1
277 w_result_real, w_result_imag = 1, 0 # 1 + 0j
278 while mask > 0 and n >= mask:
279 if n & mask:
280 w_result_real, w_result_imag = W_ComplexObject.mul_components(
281 w_result_real, w_result_imag, self_real, self_imag)
282 mask <<= 1
283 self_real, self_imag = W_ComplexObject.mul_components(self_real, self_imag, self_real, self_imag)
284
285 return W_ComplexObject(w_result_real, w_result_imag)
286
287 def is_w(self, space, w_other):
288 from rpython.rlib.longlong2float import float2longlong
289 if not isinstance(w_other, W_ComplexObject):
290 return False
291 if self.user_overridden_class or w_other.user_overridden_class:
292 return self is w_other
293 real1 = space.float_w(space.getattr(self, space.newtext("real")))
294 real2 = space.float_w(space.getattr(w_other, space.newtext("real")))
295 imag1 = space.float_w(space.getattr(self, space.newtext("imag")))
296 imag2 = space.float_w(space.getattr(w_other, space.newtext("imag")))
297 real1 = float2longlong(real1)
298 real2 = float2longlong(real2)
299 imag1 = float2longlong(imag1)
300 imag2 = float2longlong(imag2)
301 return real1 == real2 and imag1 == imag2
302
303 def immutable_unique_id(self, space):
304 if self.user_overridden_class:
305 return None
306 from rpython.rlib.longlong2float import float2longlong
307 from pypy.objspace.std.util import IDTAG_COMPLEX as tag
308 from pypy.objspace.std.util import IDTAG_SHIFT
309 real = space.float_w(space.getattr(self, space.newtext("real")))
310 imag = space.float_w(space.getattr(self, space.newtext("imag")))
311 real_b = rbigint.fromrarith_int(float2longlong(real))
312 imag_b = rbigint.fromrarith_int(r_ulonglong(float2longlong(imag)))
313 val = real_b.lshift(64).or_(imag_b).lshift(IDTAG_SHIFT).int_or_(tag)
314 return space.newlong_from_rbigint(val)
315
316 def _to_complex(self, space, w_obj):
317 if isinstance(w_obj, W_ComplexObject):
318 return w_obj
319 if space.isinstance_w(w_obj, space.w_int):
320 w_float = space.float_w(w_obj)
321 return W_ComplexObject(w_float, 0.0)
322 if space.isinstance_w(w_obj, space.w_float):
323 return W_ComplexObject(space.float_w(w_obj), 0.0)
324
325 @staticmethod
326 @unwrap_spec(w_real=WrappedDefault(0.0))
327 def descr__new__(space, w_complextype, w_real, w_imag=None):
328 # if w_real is already a complex number and there is no second
329 # argument, return it. Note that we cannot return w_real if
330 # it is an instance of a *subclass* of complex, or if w_complextype
331 # is itself a subclass of complex.
332 noarg2 = w_imag is None
333 if (noarg2 and space.is_w(w_complextype, space.w_complex)
334 and space.is_w(space.type(w_real), space.w_complex)):
335 return w_real
336
337 if space.isinstance_w(w_real, space.w_text):
338 # a string argument
339 if not noarg2:
340 raise oefmt(space.w_TypeError, "complex() can't take second"
341 " arg if first is a string")
342 unistr = unicode_to_decimal_w(space, w_real)
343 try:
344 unistr = _remove_underscores(unistr)
345 except ValueError:
346 raise oefmt(space.w_ValueError,
347 "complex() arg is a malformed string")
348 try:
349 realstr, imagstr = _split_complex(unistr)
350 except ValueError:
351 raise oefmt(space.w_ValueError,
352 "complex() arg is a malformed string")
353 try:
354 realval = string_to_float(realstr)
355 imagval = string_to_float(imagstr)
356 except ParseStringError:
357 raise oefmt(space.w_ValueError,
358 "complex() arg is a malformed string")
359
360 else:
361 # non-string arguments
362 realval, imagval = unpackcomplex(space, w_real)
363
364 # now take w_imag into account
365 if not noarg2:
366 # complex(x, y) == x+y*j, even if 'y' is already a complex.
367 realval2, imagval2 = unpackcomplex(space, w_imag,
368 firstarg=False)
369
370 # try to preserve the signs of zeroes of realval and realval2
371 if imagval2 != 0.0:
372 realval -= imagval2
373
374 if imagval != 0.0:
375 imagval += realval2
376 else:
377 imagval = realval2
378 # done
379 w_obj = space.allocate_instance(W_ComplexObject, w_complextype)
380 W_ComplexObject.__init__(w_obj, realval, imagval)
381 return w_obj
382
383 def descr___getnewargs__(self, space):
384 return space.newtuple2(space.newfloat(self.realval),
385 space.newfloat(self.imagval))
386
387 def descr_repr(self, space):
388 if self.realval == 0 and math.copysign(1., self.realval) == 1.:
389 return space.newtext(repr_format(self.imagval) + 'j')
390 sign = (math.copysign(1., self.imagval) == 1. or
391 math.isnan(self.imagval)) and '+' or ''
392 return space.newtext('(' + repr_format(self.realval)
393 + sign + repr_format(self.imagval) + 'j)')
394
395 def descr_hash(self, space):
396 if math.isnan(self.realval):
397 hashreal = space.int_w(default_identity_hash(space, self))
398 else:
399 hashreal = _hash_float(self.realval)
400 if math.isnan(self.imagval):
401 hashimg = space.int_w(default_identity_hash(space, self))
402 else:
403 hashimg = _hash_float(self.imagval)
404 h = intmask(hashreal + HASH_IMAG * hashimg)
405 h -= (h == -1)
406 return space.newint(h)
407
408 def descr_coerce(self, space, w_other):
409 w_other = self._to_complex(space, w_other)
410 if w_other is None:
411 return space.w_NotImplemented
412 return space.newtuple2(self, w_other)
413
414 def descr_format(self, space, w_format_spec):
415 return newformat.run_formatter(space, w_format_spec, "format_complex",
416 self)
417
418 def descr_bool(self, space):
419 return space.newbool((self.realval != 0.0) or (self.imagval != 0.0))
420
421 def descr_neg(self, space):
422 return W_ComplexObject(-self.realval, -self.imagval)
423
424 def descr_pos(self, space):
425 return W_ComplexObject(self.realval, self.imagval)
426
427 def descr_complex(self, space):
428 """Convert this value to exact type complex."""
429 return W_ComplexObject(self.realval, self.imagval)
430
431 def descr_abs(self, space):
432 try:
433 return space.newfloat(math.hypot(self.realval, self.imagval))
434 except OverflowError as e:
435 raise OperationError(space.w_OverflowError, space.newtext(str(e)))
436
437 def descr_eq(self, space, w_other):
438 if isinstance(w_other, W_ComplexObject):
439 return space.newbool((self.realval == w_other.realval) and
440 (self.imagval == w_other.imagval))
441 if (space.isinstance_w(w_other, space.w_int) or
442 space.isinstance_w(w_other, space.w_float)):
443 if self.imagval:
444 return space.w_False
445 return space.eq(space.newfloat(self.realval), w_other)
446 return space.w_NotImplemented
447
448 def descr_ne(self, space, w_other):
449 if isinstance(w_other, W_ComplexObject):
450 return space.newbool((self.realval != w_other.realval) or
451 (self.imagval != w_other.imagval))
452 if (space.isinstance_w(w_other, space.w_int) or
453 space.isinstance_w(w_other, space.w_float)):
454 if self.imagval:
455 return space.w_True
456 return space.ne(space.newfloat(self.realval), w_other)
457 return space.w_NotImplemented
458
459 def _fail_cmp(self, space, w_other):
460 return space.w_NotImplemented
461
462 def descr_add(self, space, w_rhs):
463 w_rhs = self._to_complex(space, w_rhs)
464 if w_rhs is None:
465 return space.w_NotImplemented
466 return W_ComplexObject(self.realval + w_rhs.realval,
467 self.imagval + w_rhs.imagval)
468
469 def descr_radd(self, space, w_lhs):
470 w_lhs = self._to_complex(space, w_lhs)
471 if w_lhs is None:
472 return space.w_NotImplemented
473 return W_ComplexObject(w_lhs.realval + self.realval,
474 w_lhs.imagval + self.imagval)
475
476 def descr_sub(self, space, w_rhs):
477 w_rhs = self._to_complex(space, w_rhs)
478 if w_rhs is None:
479 return space.w_NotImplemented
480 return W_ComplexObject(self.realval - w_rhs.realval,
481 self.imagval - w_rhs.imagval)
482
483 def descr_rsub(self, space, w_lhs):
484 w_lhs = self._to_complex(space, w_lhs)
485 if w_lhs is None:
486 return space.w_NotImplemented
487 return W_ComplexObject(w_lhs.realval - self.realval,
488 w_lhs.imagval - self.imagval)
489
490 def descr_mul(self, space, w_rhs):
491 w_rhs = self._to_complex(space, w_rhs)
492 if w_rhs is None:
493 return space.w_NotImplemented
494 return self.mul(w_rhs)
495
496 def descr_rmul(self, space, w_lhs):
497 w_lhs = self._to_complex(space, w_lhs)
498 if w_lhs is None:
499 return space.w_NotImplemented
500 return w_lhs.mul(self)
501
502 def descr_truediv(self, space, w_rhs):
503 w_rhs = self._to_complex(space, w_rhs)
504 if w_rhs is None:
505 return space.w_NotImplemented
506 try:
507 return self.div(w_rhs)
508 except ZeroDivisionError as e:
509 raise oefmt(space.w_ZeroDivisionError, "complex division by zero")
510
511 def descr_rtruediv(self, space, w_lhs):
512 w_lhs = self._to_complex(space, w_lhs)
513 if w_lhs is None:
514 return space.w_NotImplemented
515 try:
516 return w_lhs.div(self)
517 except ZeroDivisionError as e:
518 raise oefmt(space.w_ZeroDivisionError, "complex division by zero")
519
520 @unwrap_spec(w_third_arg=WrappedDefault(None))
521 def descr_pow(self, space, w_exponent, w_third_arg):
522 w_exponent = self._to_complex(space, w_exponent)
523 if w_exponent is None:
524 return space.w_NotImplemented
525 if not space.is_w(w_third_arg, space.w_None):
526 raise oefmt(space.w_ValueError, 'complex modulo')
527 try:
528 r = w_exponent.realval
529 if (w_exponent.imagval == 0.0 and -100.0 <= r <= 100.0 and
530 r == int(r)):
531 w_p = self.pow_small_int(int(r))
532 else:
533 w_p = self.pow(w_exponent)
534 except ZeroDivisionError:
535 raise oefmt(space.w_ZeroDivisionError,
536 "0.0 to a negative or complex power")
537 except OverflowError:
538 raise oefmt(space.w_OverflowError, "complex exponentiation")
539 return w_p
540
541 @unwrap_spec(w_third_arg=WrappedDefault(None))
542 def descr_rpow(self, space, w_lhs, w_third_arg):
543 w_lhs = self._to_complex(space, w_lhs)
544 if w_lhs is None:
545 return space.w_NotImplemented
546 return w_lhs.descr_pow(space, self, w_third_arg)
547
548 def descr_conjugate(self, space):
549 """(A+Bj).conjugate() -> A-Bj"""
550 return space.newcomplex(self.realval, -self.imagval)
551
552
553 w_one = W_ComplexObject(1, 0)
554
555
556 def complexwprop(name, doc):
557 def fget(space, w_obj):
558 if not isinstance(w_obj, W_ComplexObject):
559 raise oefmt(space.w_TypeError, "descriptor is for 'complex'")
560 return space.newfloat(getattr(w_obj, name))
561 return GetSetProperty(fget, doc=doc, cls=W_ComplexObject)
562
563 W_ComplexObject.typedef = TypeDef("complex",
564 __doc__ = """complex(real=0, imag=0)
565 --
566
567 Create a complex number from a real part and an optional imaginary part.
568 This is equivalent to (real + imag*1j) where imag defaults to 0.""",
569 __new__ = interp2app(W_ComplexObject.descr__new__),
570 __getnewargs__ = interp2app(W_ComplexObject.descr___getnewargs__),
571 real = complexwprop('realval', doc="the real part of a complex number"),
572 imag = complexwprop('imagval',
573 doc="the imaginary part of a complex number"),
574 __repr__ = interp2app(W_ComplexObject.descr_repr),
575 __hash__ = interp2app(W_ComplexObject.descr_hash),
576 __format__ = interp2app(W_ComplexObject.descr_format),
577 __bool__ = interp2app(W_ComplexObject.descr_bool),
578 __neg__ = interp2app(W_ComplexObject.descr_neg),
579 __pos__ = interp2app(W_ComplexObject.descr_pos),
580 __abs__ = interp2app(W_ComplexObject.descr_abs),
581
582 __eq__ = interp2app(W_ComplexObject.descr_eq),
583 __ne__ = interp2app(W_ComplexObject.descr_ne),
584 __lt__ = interp2app(W_ComplexObject._fail_cmp),
585 __le__ = interp2app(W_ComplexObject._fail_cmp),
586 __gt__ = interp2app(W_ComplexObject._fail_cmp),
587 __ge__ = interp2app(W_ComplexObject._fail_cmp),
588
589 __add__ = interp2app(W_ComplexObject.descr_add),
590 __radd__ = interp2app(W_ComplexObject.descr_radd),
591 __sub__ = interp2app(W_ComplexObject.descr_sub),
592 __rsub__ = interp2app(W_ComplexObject.descr_rsub),
593 __mul__ = interp2app(W_ComplexObject.descr_mul),
594 __rmul__ = interp2app(W_ComplexObject.descr_rmul),
595 __truediv__ = interp2app(W_ComplexObject.descr_truediv),
596 __rtruediv__ = interp2app(W_ComplexObject.descr_rtruediv),
597 __pow__ = interp2app(W_ComplexObject.descr_pow),
598 __rpow__ = interp2app(W_ComplexObject.descr_rpow),
599
600 conjugate = interp2app(W_ComplexObject.descr_conjugate),
601 __complex__ = interp2app(W_ComplexObject.descr_complex),
602 )