Coverage Report

Created: 2025-07-11 06:59

/src/Python-3.8.3/Objects/complexobject.c
Line
Count
Source (jump to first uncovered line)
1
2
/* Complex object implementation */
3
4
/* Borrows heavily from floatobject.c */
5
6
/* Submitted by Jim Hugunin */
7
8
#include "Python.h"
9
#include "structmember.h"
10
11
/*[clinic input]
12
class complex "PyComplexObject *" "&PyComplex_Type"
13
[clinic start generated code]*/
14
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=819e057d2d10f5ec]*/
15
16
#include "clinic/complexobject.c.h"
17
18
/* elementary operations on complex numbers */
19
20
static Py_complex c_1 = {1., 0.};
21
22
Py_complex
23
_Py_c_sum(Py_complex a, Py_complex b)
24
0
{
25
0
    Py_complex r;
26
0
    r.real = a.real + b.real;
27
0
    r.imag = a.imag + b.imag;
28
0
    return r;
29
0
}
30
31
Py_complex
32
_Py_c_diff(Py_complex a, Py_complex b)
33
0
{
34
0
    Py_complex r;
35
0
    r.real = a.real - b.real;
36
0
    r.imag = a.imag - b.imag;
37
0
    return r;
38
0
}
39
40
Py_complex
41
_Py_c_neg(Py_complex a)
42
0
{
43
0
    Py_complex r;
44
0
    r.real = -a.real;
45
0
    r.imag = -a.imag;
46
0
    return r;
47
0
}
48
49
Py_complex
50
_Py_c_prod(Py_complex a, Py_complex b)
51
0
{
52
0
    Py_complex r;
53
0
    r.real = a.real*b.real - a.imag*b.imag;
54
0
    r.imag = a.real*b.imag + a.imag*b.real;
55
0
    return r;
56
0
}
57
58
/* Avoid bad optimization on Windows ARM64 until the compiler is fixed */
59
#ifdef _M_ARM64
60
#pragma optimize("", off)
61
#endif
62
Py_complex
63
_Py_c_quot(Py_complex a, Py_complex b)
64
0
{
65
    /******************************************************************
66
    This was the original algorithm.  It's grossly prone to spurious
67
    overflow and underflow errors.  It also merrily divides by 0 despite
68
    checking for that(!).  The code still serves a doc purpose here, as
69
    the algorithm following is a simple by-cases transformation of this
70
    one:
71
72
    Py_complex r;
73
    double d = b.real*b.real + b.imag*b.imag;
74
    if (d == 0.)
75
        errno = EDOM;
76
    r.real = (a.real*b.real + a.imag*b.imag)/d;
77
    r.imag = (a.imag*b.real - a.real*b.imag)/d;
78
    return r;
79
    ******************************************************************/
80
81
    /* This algorithm is better, and is pretty obvious:  first divide the
82
     * numerators and denominator by whichever of {b.real, b.imag} has
83
     * larger magnitude.  The earliest reference I found was to CACM
84
     * Algorithm 116 (Complex Division, Robert L. Smith, Stanford
85
     * University).  As usual, though, we're still ignoring all IEEE
86
     * endcases.
87
     */
88
0
     Py_complex r;      /* the result */
89
0
     const double abs_breal = b.real < 0 ? -b.real : b.real;
90
0
     const double abs_bimag = b.imag < 0 ? -b.imag : b.imag;
91
92
0
    if (abs_breal >= abs_bimag) {
93
        /* divide tops and bottom by b.real */
94
0
        if (abs_breal == 0.0) {
95
0
            errno = EDOM;
96
0
            r.real = r.imag = 0.0;
97
0
        }
98
0
        else {
99
0
            const double ratio = b.imag / b.real;
100
0
            const double denom = b.real + b.imag * ratio;
101
0
            r.real = (a.real + a.imag * ratio) / denom;
102
0
            r.imag = (a.imag - a.real * ratio) / denom;
103
0
        }
104
0
    }
105
0
    else if (abs_bimag >= abs_breal) {
106
        /* divide tops and bottom by b.imag */
107
0
        const double ratio = b.real / b.imag;
108
0
        const double denom = b.real * ratio + b.imag;
109
0
        assert(b.imag != 0.0);
110
0
        r.real = (a.real * ratio + a.imag) / denom;
111
0
        r.imag = (a.imag * ratio - a.real) / denom;
112
0
    }
113
0
    else {
114
        /* At least one of b.real or b.imag is a NaN */
115
0
        r.real = r.imag = Py_NAN;
116
0
    }
117
0
    return r;
118
0
}
119
#ifdef _M_ARM64
120
#pragma optimize("", on)
121
#endif
122
123
Py_complex
124
_Py_c_pow(Py_complex a, Py_complex b)
125
0
{
126
0
    Py_complex r;
127
0
    double vabs,len,at,phase;
128
0
    if (b.real == 0. && b.imag == 0.) {
129
0
        r.real = 1.;
130
0
        r.imag = 0.;
131
0
    }
132
0
    else if (a.real == 0. && a.imag == 0.) {
133
0
        if (b.imag != 0. || b.real < 0.)
134
0
            errno = EDOM;
135
0
        r.real = 0.;
136
0
        r.imag = 0.;
137
0
    }
138
0
    else {
139
0
        vabs = hypot(a.real,a.imag);
140
0
        len = pow(vabs,b.real);
141
0
        at = atan2(a.imag, a.real);
142
0
        phase = at*b.real;
143
0
        if (b.imag != 0.0) {
144
0
            len /= exp(at*b.imag);
145
0
            phase += b.imag*log(vabs);
146
0
        }
147
0
        r.real = len*cos(phase);
148
0
        r.imag = len*sin(phase);
149
0
    }
150
0
    return r;
151
0
}
152
153
static Py_complex
154
c_powu(Py_complex x, long n)
155
0
{
156
0
    Py_complex r, p;
157
0
    long mask = 1;
158
0
    r = c_1;
159
0
    p = x;
160
0
    while (mask > 0 && n >= mask) {
161
0
        if (n & mask)
162
0
            r = _Py_c_prod(r,p);
163
0
        mask <<= 1;
164
0
        p = _Py_c_prod(p,p);
165
0
    }
166
0
    return r;
167
0
}
168
169
static Py_complex
170
c_powi(Py_complex x, long n)
171
0
{
172
0
    Py_complex cn;
173
174
0
    if (n > 100 || n < -100) {
175
0
        cn.real = (double) n;
176
0
        cn.imag = 0.;
177
0
        return _Py_c_pow(x,cn);
178
0
    }
179
0
    else if (n > 0)
180
0
        return c_powu(x,n);
181
0
    else
182
0
        return _Py_c_quot(c_1, c_powu(x,-n));
183
184
0
}
185
186
double
187
_Py_c_abs(Py_complex z)
188
0
{
189
    /* sets errno = ERANGE on overflow;  otherwise errno = 0 */
190
0
    double result;
191
192
0
    if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) {
193
        /* C99 rules: if either the real or the imaginary part is an
194
           infinity, return infinity, even if the other part is a
195
           NaN. */
196
0
        if (Py_IS_INFINITY(z.real)) {
197
0
            result = fabs(z.real);
198
0
            errno = 0;
199
0
            return result;
200
0
        }
201
0
        if (Py_IS_INFINITY(z.imag)) {
202
0
            result = fabs(z.imag);
203
0
            errno = 0;
204
0
            return result;
205
0
        }
206
        /* either the real or imaginary part is a NaN,
207
           and neither is infinite. Result should be NaN. */
208
0
        return Py_NAN;
209
0
    }
210
0
    result = hypot(z.real, z.imag);
211
0
    if (!Py_IS_FINITE(result))
212
0
        errno = ERANGE;
213
0
    else
214
0
        errno = 0;
215
0
    return result;
216
0
}
217
218
static PyObject *
219
complex_subtype_from_c_complex(PyTypeObject *type, Py_complex cval)
220
0
{
221
0
    PyObject *op;
222
223
0
    op = type->tp_alloc(type, 0);
224
0
    if (op != NULL)
225
0
        ((PyComplexObject *)op)->cval = cval;
226
0
    return op;
227
0
}
228
229
PyObject *
230
PyComplex_FromCComplex(Py_complex cval)
231
0
{
232
0
    PyComplexObject *op;
233
234
    /* Inline PyObject_New */
235
0
    op = (PyComplexObject *) PyObject_MALLOC(sizeof(PyComplexObject));
236
0
    if (op == NULL)
237
0
        return PyErr_NoMemory();
238
0
    (void)PyObject_INIT(op, &PyComplex_Type);
239
0
    op->cval = cval;
240
0
    return (PyObject *) op;
241
0
}
242
243
static PyObject *
244
complex_subtype_from_doubles(PyTypeObject *type, double real, double imag)
245
0
{
246
0
    Py_complex c;
247
0
    c.real = real;
248
0
    c.imag = imag;
249
0
    return complex_subtype_from_c_complex(type, c);
250
0
}
251
252
PyObject *
253
PyComplex_FromDoubles(double real, double imag)
254
0
{
255
0
    Py_complex c;
256
0
    c.real = real;
257
0
    c.imag = imag;
258
0
    return PyComplex_FromCComplex(c);
259
0
}
260
261
double
262
PyComplex_RealAsDouble(PyObject *op)
263
0
{
264
0
    if (PyComplex_Check(op)) {
265
0
        return ((PyComplexObject *)op)->cval.real;
266
0
    }
267
0
    else {
268
0
        return PyFloat_AsDouble(op);
269
0
    }
270
0
}
271
272
double
273
PyComplex_ImagAsDouble(PyObject *op)
274
0
{
275
0
    if (PyComplex_Check(op)) {
276
0
        return ((PyComplexObject *)op)->cval.imag;
277
0
    }
278
0
    else {
279
0
        return 0.0;
280
0
    }
281
0
}
282
283
static PyObject *
284
try_complex_special_method(PyObject *op)
285
0
{
286
0
    PyObject *f;
287
0
    _Py_IDENTIFIER(__complex__);
288
289
0
    f = _PyObject_LookupSpecial(op, &PyId___complex__);
290
0
    if (f) {
291
0
        PyObject *res = _PyObject_CallNoArg(f);
292
0
        Py_DECREF(f);
293
0
        if (!res || PyComplex_CheckExact(res)) {
294
0
            return res;
295
0
        }
296
0
        if (!PyComplex_Check(res)) {
297
0
            PyErr_Format(PyExc_TypeError,
298
0
                "__complex__ returned non-complex (type %.200s)",
299
0
                res->ob_type->tp_name);
300
0
            Py_DECREF(res);
301
0
            return NULL;
302
0
        }
303
        /* Issue #29894: warn if 'res' not of exact type complex. */
304
0
        if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
305
0
                "__complex__ returned non-complex (type %.200s).  "
306
0
                "The ability to return an instance of a strict subclass of complex "
307
0
                "is deprecated, and may be removed in a future version of Python.",
308
0
                res->ob_type->tp_name)) {
309
0
            Py_DECREF(res);
310
0
            return NULL;
311
0
        }
312
0
        return res;
313
0
    }
314
0
    return NULL;
315
0
}
316
317
Py_complex
318
PyComplex_AsCComplex(PyObject *op)
319
0
{
320
0
    Py_complex cv;
321
0
    PyObject *newop = NULL;
322
323
0
    assert(op);
324
    /* If op is already of type PyComplex_Type, return its value */
325
0
    if (PyComplex_Check(op)) {
326
0
        return ((PyComplexObject *)op)->cval;
327
0
    }
328
    /* If not, use op's __complex__  method, if it exists */
329
330
    /* return -1 on failure */
331
0
    cv.real = -1.;
332
0
    cv.imag = 0.;
333
334
0
    newop = try_complex_special_method(op);
335
336
0
    if (newop) {
337
0
        cv = ((PyComplexObject *)newop)->cval;
338
0
        Py_DECREF(newop);
339
0
        return cv;
340
0
    }
341
0
    else if (PyErr_Occurred()) {
342
0
        return cv;
343
0
    }
344
    /* If neither of the above works, interpret op as a float giving the
345
       real part of the result, and fill in the imaginary part as 0. */
346
0
    else {
347
        /* PyFloat_AsDouble will return -1 on failure */
348
0
        cv.real = PyFloat_AsDouble(op);
349
0
        return cv;
350
0
    }
351
0
}
352
353
static PyObject *
354
complex_repr(PyComplexObject *v)
355
0
{
356
0
    int precision = 0;
357
0
    char format_code = 'r';
358
0
    PyObject *result = NULL;
359
360
    /* If these are non-NULL, they'll need to be freed. */
361
0
    char *pre = NULL;
362
0
    char *im = NULL;
363
364
    /* These do not need to be freed. re is either an alias
365
       for pre or a pointer to a constant.  lead and tail
366
       are pointers to constants. */
367
0
    const char *re = NULL;
368
0
    const char *lead = "";
369
0
    const char *tail = "";
370
371
0
    if (v->cval.real == 0. && copysign(1.0, v->cval.real)==1.0) {
372
        /* Real part is +0: just output the imaginary part and do not
373
           include parens. */
374
0
        re = "";
375
0
        im = PyOS_double_to_string(v->cval.imag, format_code,
376
0
                                   precision, 0, NULL);
377
0
        if (!im) {
378
0
            PyErr_NoMemory();
379
0
            goto done;
380
0
        }
381
0
    } else {
382
        /* Format imaginary part with sign, real part without. Include
383
           parens in the result. */
384
0
        pre = PyOS_double_to_string(v->cval.real, format_code,
385
0
                                    precision, 0, NULL);
386
0
        if (!pre) {
387
0
            PyErr_NoMemory();
388
0
            goto done;
389
0
        }
390
0
        re = pre;
391
392
0
        im = PyOS_double_to_string(v->cval.imag, format_code,
393
0
                                   precision, Py_DTSF_SIGN, NULL);
394
0
        if (!im) {
395
0
            PyErr_NoMemory();
396
0
            goto done;
397
0
        }
398
0
        lead = "(";
399
0
        tail = ")";
400
0
    }
401
0
    result = PyUnicode_FromFormat("%s%s%sj%s", lead, re, im, tail);
402
0
  done:
403
0
    PyMem_Free(im);
404
0
    PyMem_Free(pre);
405
406
0
    return result;
407
0
}
408
409
static Py_hash_t
410
complex_hash(PyComplexObject *v)
411
0
{
412
0
    Py_uhash_t hashreal, hashimag, combined;
413
0
    hashreal = (Py_uhash_t)_Py_HashDouble(v->cval.real);
414
0
    if (hashreal == (Py_uhash_t)-1)
415
0
        return -1;
416
0
    hashimag = (Py_uhash_t)_Py_HashDouble(v->cval.imag);
417
0
    if (hashimag == (Py_uhash_t)-1)
418
0
        return -1;
419
    /* Note:  if the imaginary part is 0, hashimag is 0 now,
420
     * so the following returns hashreal unchanged.  This is
421
     * important because numbers of different types that
422
     * compare equal must have the same hash value, so that
423
     * hash(x + 0*j) must equal hash(x).
424
     */
425
0
    combined = hashreal + _PyHASH_IMAG * hashimag;
426
0
    if (combined == (Py_uhash_t)-1)
427
0
        combined = (Py_uhash_t)-2;
428
0
    return (Py_hash_t)combined;
429
0
}
430
431
/* This macro may return! */
432
#define TO_COMPLEX(obj, c) \
433
0
    if (PyComplex_Check(obj)) \
434
0
        c = ((PyComplexObject *)(obj))->cval; \
435
0
    else if (to_complex(&(obj), &(c)) < 0) \
436
0
        return (obj)
437
438
static int
439
to_complex(PyObject **pobj, Py_complex *pc)
440
0
{
441
0
    PyObject *obj = *pobj;
442
443
0
    pc->real = pc->imag = 0.0;
444
0
    if (PyLong_Check(obj)) {
445
0
        pc->real = PyLong_AsDouble(obj);
446
0
        if (pc->real == -1.0 && PyErr_Occurred()) {
447
0
            *pobj = NULL;
448
0
            return -1;
449
0
        }
450
0
        return 0;
451
0
    }
452
0
    if (PyFloat_Check(obj)) {
453
0
        pc->real = PyFloat_AsDouble(obj);
454
0
        return 0;
455
0
    }
456
0
    Py_INCREF(Py_NotImplemented);
457
0
    *pobj = Py_NotImplemented;
458
0
    return -1;
459
0
}
460
461
462
static PyObject *
463
complex_add(PyObject *v, PyObject *w)
464
0
{
465
0
    Py_complex result;
466
0
    Py_complex a, b;
467
0
    TO_COMPLEX(v, a);
468
0
    TO_COMPLEX(w, b);
469
0
    PyFPE_START_PROTECT("complex_add", return 0)
470
0
    result = _Py_c_sum(a, b);
471
0
    PyFPE_END_PROTECT(result)
472
0
    return PyComplex_FromCComplex(result);
473
0
}
474
475
static PyObject *
476
complex_sub(PyObject *v, PyObject *w)
477
0
{
478
0
    Py_complex result;
479
0
    Py_complex a, b;
480
0
    TO_COMPLEX(v, a);
481
0
    TO_COMPLEX(w, b);
482
0
    PyFPE_START_PROTECT("complex_sub", return 0)
483
0
    result = _Py_c_diff(a, b);
484
0
    PyFPE_END_PROTECT(result)
485
0
    return PyComplex_FromCComplex(result);
486
0
}
487
488
static PyObject *
489
complex_mul(PyObject *v, PyObject *w)
490
0
{
491
0
    Py_complex result;
492
0
    Py_complex a, b;
493
0
    TO_COMPLEX(v, a);
494
0
    TO_COMPLEX(w, b);
495
0
    PyFPE_START_PROTECT("complex_mul", return 0)
496
0
    result = _Py_c_prod(a, b);
497
0
    PyFPE_END_PROTECT(result)
498
0
    return PyComplex_FromCComplex(result);
499
0
}
500
501
static PyObject *
502
complex_div(PyObject *v, PyObject *w)
503
0
{
504
0
    Py_complex quot;
505
0
    Py_complex a, b;
506
0
    TO_COMPLEX(v, a);
507
0
    TO_COMPLEX(w, b);
508
0
    PyFPE_START_PROTECT("complex_div", return 0)
509
0
    errno = 0;
510
0
    quot = _Py_c_quot(a, b);
511
0
    PyFPE_END_PROTECT(quot)
512
0
    if (errno == EDOM) {
513
0
        PyErr_SetString(PyExc_ZeroDivisionError, "complex division by zero");
514
0
        return NULL;
515
0
    }
516
0
    return PyComplex_FromCComplex(quot);
517
0
}
518
519
static PyObject *
520
complex_remainder(PyObject *v, PyObject *w)
521
0
{
522
0
    PyErr_SetString(PyExc_TypeError,
523
0
                    "can't mod complex numbers.");
524
0
    return NULL;
525
0
}
526
527
528
static PyObject *
529
complex_divmod(PyObject *v, PyObject *w)
530
0
{
531
0
    PyErr_SetString(PyExc_TypeError,
532
0
                    "can't take floor or mod of complex number.");
533
0
    return NULL;
534
0
}
535
536
static PyObject *
537
complex_pow(PyObject *v, PyObject *w, PyObject *z)
538
0
{
539
0
    Py_complex p;
540
0
    Py_complex exponent;
541
0
    long int_exponent;
542
0
    Py_complex a, b;
543
0
    TO_COMPLEX(v, a);
544
0
    TO_COMPLEX(w, b);
545
546
0
    if (z != Py_None) {
547
0
        PyErr_SetString(PyExc_ValueError, "complex modulo");
548
0
        return NULL;
549
0
    }
550
0
    PyFPE_START_PROTECT("complex_pow", return 0)
551
0
    errno = 0;
552
0
    exponent = b;
553
0
    int_exponent = (long)exponent.real;
554
0
    if (exponent.imag == 0. && exponent.real == int_exponent)
555
0
        p = c_powi(a, int_exponent);
556
0
    else
557
0
        p = _Py_c_pow(a, exponent);
558
559
0
    PyFPE_END_PROTECT(p)
560
0
    Py_ADJUST_ERANGE2(p.real, p.imag);
561
0
    if (errno == EDOM) {
562
0
        PyErr_SetString(PyExc_ZeroDivisionError,
563
0
                        "0.0 to a negative or complex power");
564
0
        return NULL;
565
0
    }
566
0
    else if (errno == ERANGE) {
567
0
        PyErr_SetString(PyExc_OverflowError,
568
0
                        "complex exponentiation");
569
0
        return NULL;
570
0
    }
571
0
    return PyComplex_FromCComplex(p);
572
0
}
573
574
static PyObject *
575
complex_int_div(PyObject *v, PyObject *w)
576
0
{
577
0
    PyErr_SetString(PyExc_TypeError,
578
0
                    "can't take floor of complex number.");
579
0
    return NULL;
580
0
}
581
582
static PyObject *
583
complex_neg(PyComplexObject *v)
584
0
{
585
0
    Py_complex neg;
586
0
    neg.real = -v->cval.real;
587
0
    neg.imag = -v->cval.imag;
588
0
    return PyComplex_FromCComplex(neg);
589
0
}
590
591
static PyObject *
592
complex_pos(PyComplexObject *v)
593
0
{
594
0
    if (PyComplex_CheckExact(v)) {
595
0
        Py_INCREF(v);
596
0
        return (PyObject *)v;
597
0
    }
598
0
    else
599
0
        return PyComplex_FromCComplex(v->cval);
600
0
}
601
602
static PyObject *
603
complex_abs(PyComplexObject *v)
604
0
{
605
0
    double result;
606
607
0
    PyFPE_START_PROTECT("complex_abs", return 0)
608
0
    result = _Py_c_abs(v->cval);
609
0
    PyFPE_END_PROTECT(result)
610
611
0
    if (errno == ERANGE) {
612
0
        PyErr_SetString(PyExc_OverflowError,
613
0
                        "absolute value too large");
614
0
        return NULL;
615
0
    }
616
0
    return PyFloat_FromDouble(result);
617
0
}
618
619
static int
620
complex_bool(PyComplexObject *v)
621
0
{
622
0
    return v->cval.real != 0.0 || v->cval.imag != 0.0;
623
0
}
624
625
static PyObject *
626
complex_richcompare(PyObject *v, PyObject *w, int op)
627
0
{
628
0
    PyObject *res;
629
0
    Py_complex i;
630
0
    int equal;
631
632
0
    if (op != Py_EQ && op != Py_NE) {
633
0
        goto Unimplemented;
634
0
    }
635
636
0
    assert(PyComplex_Check(v));
637
0
    TO_COMPLEX(v, i);
638
639
0
    if (PyLong_Check(w)) {
640
        /* Check for 0.0 imaginary part first to avoid the rich
641
         * comparison when possible.
642
         */
643
0
        if (i.imag == 0.0) {
644
0
            PyObject *j, *sub_res;
645
0
            j = PyFloat_FromDouble(i.real);
646
0
            if (j == NULL)
647
0
                return NULL;
648
649
0
            sub_res = PyObject_RichCompare(j, w, op);
650
0
            Py_DECREF(j);
651
0
            return sub_res;
652
0
        }
653
0
        else {
654
0
            equal = 0;
655
0
        }
656
0
    }
657
0
    else if (PyFloat_Check(w)) {
658
0
        equal = (i.real == PyFloat_AsDouble(w) && i.imag == 0.0);
659
0
    }
660
0
    else if (PyComplex_Check(w)) {
661
0
        Py_complex j;
662
663
0
        TO_COMPLEX(w, j);
664
0
        equal = (i.real == j.real && i.imag == j.imag);
665
0
    }
666
0
    else {
667
0
        goto Unimplemented;
668
0
    }
669
670
0
    if (equal == (op == Py_EQ))
671
0
         res = Py_True;
672
0
    else
673
0
         res = Py_False;
674
675
0
    Py_INCREF(res);
676
0
    return res;
677
678
0
Unimplemented:
679
0
    Py_RETURN_NOTIMPLEMENTED;
680
0
}
681
682
static PyObject *
683
complex_int(PyObject *v)
684
0
{
685
0
    PyErr_SetString(PyExc_TypeError,
686
0
               "can't convert complex to int");
687
0
    return NULL;
688
0
}
689
690
static PyObject *
691
complex_float(PyObject *v)
692
0
{
693
0
    PyErr_SetString(PyExc_TypeError,
694
0
               "can't convert complex to float");
695
0
    return NULL;
696
0
}
697
698
static PyObject *
699
complex_conjugate(PyObject *self, PyObject *Py_UNUSED(ignored))
700
0
{
701
0
    Py_complex c;
702
0
    c = ((PyComplexObject *)self)->cval;
703
0
    c.imag = -c.imag;
704
0
    return PyComplex_FromCComplex(c);
705
0
}
706
707
PyDoc_STRVAR(complex_conjugate_doc,
708
"complex.conjugate() -> complex\n"
709
"\n"
710
"Return the complex conjugate of its argument. (3-4j).conjugate() == 3+4j.");
711
712
static PyObject *
713
complex_getnewargs(PyComplexObject *v, PyObject *Py_UNUSED(ignored))
714
0
{
715
0
    Py_complex c = v->cval;
716
0
    return Py_BuildValue("(dd)", c.real, c.imag);
717
0
}
718
719
PyDoc_STRVAR(complex__format__doc,
720
"complex.__format__() -> str\n"
721
"\n"
722
"Convert to a string according to format_spec.");
723
724
static PyObject *
725
complex__format__(PyObject* self, PyObject* args)
726
0
{
727
0
    PyObject *format_spec;
728
0
    _PyUnicodeWriter writer;
729
0
    int ret;
730
731
0
    if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
732
0
        return NULL;
733
734
0
    _PyUnicodeWriter_Init(&writer);
735
0
    ret = _PyComplex_FormatAdvancedWriter(
736
0
        &writer,
737
0
        self,
738
0
        format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
739
0
    if (ret == -1) {
740
0
        _PyUnicodeWriter_Dealloc(&writer);
741
0
        return NULL;
742
0
    }
743
0
    return _PyUnicodeWriter_Finish(&writer);
744
0
}
745
746
static PyMethodDef complex_methods[] = {
747
    {"conjugate",       (PyCFunction)complex_conjugate, METH_NOARGS,
748
     complex_conjugate_doc},
749
    {"__getnewargs__",          (PyCFunction)complex_getnewargs,        METH_NOARGS},
750
    {"__format__",          (PyCFunction)complex__format__,
751
                                       METH_VARARGS, complex__format__doc},
752
    {NULL,              NULL}           /* sentinel */
753
};
754
755
static PyMemberDef complex_members[] = {
756
    {"real", T_DOUBLE, offsetof(PyComplexObject, cval.real), READONLY,
757
     "the real part of a complex number"},
758
    {"imag", T_DOUBLE, offsetof(PyComplexObject, cval.imag), READONLY,
759
     "the imaginary part of a complex number"},
760
    {0},
761
};
762
763
static PyObject *
764
complex_from_string_inner(const char *s, Py_ssize_t len, void *type)
765
0
{
766
0
    double x=0.0, y=0.0, z;
767
0
    int got_bracket=0;
768
0
    const char *start;
769
0
    char *end;
770
771
    /* position on first nonblank */
772
0
    start = s;
773
0
    while (Py_ISSPACE(*s))
774
0
        s++;
775
0
    if (*s == '(') {
776
        /* Skip over possible bracket from repr(). */
777
0
        got_bracket = 1;
778
0
        s++;
779
0
        while (Py_ISSPACE(*s))
780
0
            s++;
781
0
    }
782
783
    /* a valid complex string usually takes one of the three forms:
784
785
         <float>                  - real part only
786
         <float>j                 - imaginary part only
787
         <float><signed-float>j   - real and imaginary parts
788
789
       where <float> represents any numeric string that's accepted by the
790
       float constructor (including 'nan', 'inf', 'infinity', etc.), and
791
       <signed-float> is any string of the form <float> whose first
792
       character is '+' or '-'.
793
794
       For backwards compatibility, the extra forms
795
796
         <float><sign>j
797
         <sign>j
798
         j
799
800
       are also accepted, though support for these forms may be removed from
801
       a future version of Python.
802
    */
803
804
    /* first look for forms starting with <float> */
805
0
    z = PyOS_string_to_double(s, &end, NULL);
806
0
    if (z == -1.0 && PyErr_Occurred()) {
807
0
        if (PyErr_ExceptionMatches(PyExc_ValueError))
808
0
            PyErr_Clear();
809
0
        else
810
0
            return NULL;
811
0
    }
812
0
    if (end != s) {
813
        /* all 4 forms starting with <float> land here */
814
0
        s = end;
815
0
        if (*s == '+' || *s == '-') {
816
            /* <float><signed-float>j | <float><sign>j */
817
0
            x = z;
818
0
            y = PyOS_string_to_double(s, &end, NULL);
819
0
            if (y == -1.0 && PyErr_Occurred()) {
820
0
                if (PyErr_ExceptionMatches(PyExc_ValueError))
821
0
                    PyErr_Clear();
822
0
                else
823
0
                    return NULL;
824
0
            }
825
0
            if (end != s)
826
                /* <float><signed-float>j */
827
0
                s = end;
828
0
            else {
829
                /* <float><sign>j */
830
0
                y = *s == '+' ? 1.0 : -1.0;
831
0
                s++;
832
0
            }
833
0
            if (!(*s == 'j' || *s == 'J'))
834
0
                goto parse_error;
835
0
            s++;
836
0
        }
837
0
        else if (*s == 'j' || *s == 'J') {
838
            /* <float>j */
839
0
            s++;
840
0
            y = z;
841
0
        }
842
0
        else
843
            /* <float> */
844
0
            x = z;
845
0
    }
846
0
    else {
847
        /* not starting with <float>; must be <sign>j or j */
848
0
        if (*s == '+' || *s == '-') {
849
            /* <sign>j */
850
0
            y = *s == '+' ? 1.0 : -1.0;
851
0
            s++;
852
0
        }
853
0
        else
854
            /* j */
855
0
            y = 1.0;
856
0
        if (!(*s == 'j' || *s == 'J'))
857
0
            goto parse_error;
858
0
        s++;
859
0
    }
860
861
    /* trailing whitespace and closing bracket */
862
0
    while (Py_ISSPACE(*s))
863
0
        s++;
864
0
    if (got_bracket) {
865
        /* if there was an opening parenthesis, then the corresponding
866
           closing parenthesis should be right here */
867
0
        if (*s != ')')
868
0
            goto parse_error;
869
0
        s++;
870
0
        while (Py_ISSPACE(*s))
871
0
            s++;
872
0
    }
873
874
    /* we should now be at the end of the string */
875
0
    if (s-start != len)
876
0
        goto parse_error;
877
878
0
    return complex_subtype_from_doubles((PyTypeObject *)type, x, y);
879
880
0
  parse_error:
881
0
    PyErr_SetString(PyExc_ValueError,
882
0
                    "complex() arg is a malformed string");
883
0
    return NULL;
884
0
}
885
886
static PyObject *
887
complex_subtype_from_string(PyTypeObject *type, PyObject *v)
888
0
{
889
0
    const char *s;
890
0
    PyObject *s_buffer = NULL, *result = NULL;
891
0
    Py_ssize_t len;
892
893
0
    if (PyUnicode_Check(v)) {
894
0
        s_buffer = _PyUnicode_TransformDecimalAndSpaceToASCII(v);
895
0
        if (s_buffer == NULL) {
896
0
            return NULL;
897
0
        }
898
0
        assert(PyUnicode_IS_ASCII(s_buffer));
899
        /* Simply get a pointer to existing ASCII characters. */
900
0
        s = PyUnicode_AsUTF8AndSize(s_buffer, &len);
901
0
        assert(s != NULL);
902
0
    }
903
0
    else {
904
0
        PyErr_Format(PyExc_TypeError,
905
0
            "complex() argument must be a string or a number, not '%.200s'",
906
0
            Py_TYPE(v)->tp_name);
907
0
        return NULL;
908
0
    }
909
910
0
    result = _Py_string_to_number_with_underscores(s, len, "complex", v, type,
911
0
                                                   complex_from_string_inner);
912
0
    Py_DECREF(s_buffer);
913
0
    return result;
914
0
}
915
916
/*[clinic input]
917
@classmethod
918
complex.__new__ as complex_new
919
    real as r: object(c_default="_PyLong_Zero") = 0
920
    imag as i: object(c_default="NULL") = 0
921
922
Create a complex number from a real part and an optional imaginary part.
923
924
This is equivalent to (real + imag*1j) where imag defaults to 0.
925
[clinic start generated code]*/
926
927
static PyObject *
928
complex_new_impl(PyTypeObject *type, PyObject *r, PyObject *i)
929
/*[clinic end generated code: output=b6c7dd577b537dc1 input=6f6b0bedba29bcb5]*/
930
0
{
931
0
    PyObject *tmp;
932
0
    PyNumberMethods *nbr, *nbi = NULL;
933
0
    Py_complex cr, ci;
934
0
    int own_r = 0;
935
0
    int cr_is_complex = 0;
936
0
    int ci_is_complex = 0;
937
938
    /* Special-case for a single argument when type(arg) is complex. */
939
0
    if (PyComplex_CheckExact(r) && i == NULL &&
940
0
        type == &PyComplex_Type) {
941
        /* Note that we can't know whether it's safe to return
942
           a complex *subclass* instance as-is, hence the restriction
943
           to exact complexes here.  If either the input or the
944
           output is a complex subclass, it will be handled below
945
           as a non-orthogonal vector.  */
946
0
        Py_INCREF(r);
947
0
        return r;
948
0
    }
949
0
    if (PyUnicode_Check(r)) {
950
0
        if (i != NULL) {
951
0
            PyErr_SetString(PyExc_TypeError,
952
0
                            "complex() can't take second arg"
953
0
                            " if first is a string");
954
0
            return NULL;
955
0
        }
956
0
        return complex_subtype_from_string(type, r);
957
0
    }
958
0
    if (i != NULL && PyUnicode_Check(i)) {
959
0
        PyErr_SetString(PyExc_TypeError,
960
0
                        "complex() second arg can't be a string");
961
0
        return NULL;
962
0
    }
963
964
0
    tmp = try_complex_special_method(r);
965
0
    if (tmp) {
966
0
        r = tmp;
967
0
        own_r = 1;
968
0
    }
969
0
    else if (PyErr_Occurred()) {
970
0
        return NULL;
971
0
    }
972
973
0
    nbr = r->ob_type->tp_as_number;
974
0
    if (nbr == NULL || (nbr->nb_float == NULL && nbr->nb_index == NULL)) {
975
0
        PyErr_Format(PyExc_TypeError,
976
0
                     "complex() first argument must be a string or a number, "
977
0
                     "not '%.200s'",
978
0
                     Py_TYPE(r)->tp_name);
979
0
        if (own_r) {
980
0
            Py_DECREF(r);
981
0
        }
982
0
        return NULL;
983
0
    }
984
0
    if (i != NULL) {
985
0
        nbi = i->ob_type->tp_as_number;
986
0
        if (nbi == NULL || (nbi->nb_float == NULL && nbi->nb_index == NULL)) {
987
0
            PyErr_Format(PyExc_TypeError,
988
0
                         "complex() second argument must be a number, "
989
0
                         "not '%.200s'",
990
0
                         Py_TYPE(i)->tp_name);
991
0
            if (own_r) {
992
0
                Py_DECREF(r);
993
0
            }
994
0
            return NULL;
995
0
        }
996
0
    }
997
998
    /* If we get this far, then the "real" and "imag" parts should
999
       both be treated as numbers, and the constructor should return a
1000
       complex number equal to (real + imag*1j).
1001
1002
       Note that we do NOT assume the input to already be in canonical
1003
       form; the "real" and "imag" parts might themselves be complex
1004
       numbers, which slightly complicates the code below. */
1005
0
    if (PyComplex_Check(r)) {
1006
        /* Note that if r is of a complex subtype, we're only
1007
           retaining its real & imag parts here, and the return
1008
           value is (properly) of the builtin complex type. */
1009
0
        cr = ((PyComplexObject*)r)->cval;
1010
0
        cr_is_complex = 1;
1011
0
        if (own_r) {
1012
0
            Py_DECREF(r);
1013
0
        }
1014
0
    }
1015
0
    else {
1016
        /* The "real" part really is entirely real, and contributes
1017
           nothing in the imaginary direction.
1018
           Just treat it as a double. */
1019
0
        tmp = PyNumber_Float(r);
1020
0
        if (own_r) {
1021
            /* r was a newly created complex number, rather
1022
               than the original "real" argument. */
1023
0
            Py_DECREF(r);
1024
0
        }
1025
0
        if (tmp == NULL)
1026
0
            return NULL;
1027
0
        assert(PyFloat_Check(tmp));
1028
0
        cr.real = PyFloat_AsDouble(tmp);
1029
0
        cr.imag = 0.0;
1030
0
        Py_DECREF(tmp);
1031
0
    }
1032
0
    if (i == NULL) {
1033
0
        ci.real = cr.imag;
1034
0
    }
1035
0
    else if (PyComplex_Check(i)) {
1036
0
        ci = ((PyComplexObject*)i)->cval;
1037
0
        ci_is_complex = 1;
1038
0
    } else {
1039
        /* The "imag" part really is entirely imaginary, and
1040
           contributes nothing in the real direction.
1041
           Just treat it as a double. */
1042
0
        tmp = PyNumber_Float(i);
1043
0
        if (tmp == NULL)
1044
0
            return NULL;
1045
0
        ci.real = PyFloat_AsDouble(tmp);
1046
0
        Py_DECREF(tmp);
1047
0
    }
1048
    /*  If the input was in canonical form, then the "real" and "imag"
1049
        parts are real numbers, so that ci.imag and cr.imag are zero.
1050
        We need this correction in case they were not real numbers. */
1051
1052
0
    if (ci_is_complex) {
1053
0
        cr.real -= ci.imag;
1054
0
    }
1055
0
    if (cr_is_complex && i != NULL) {
1056
0
        ci.real += cr.imag;
1057
0
    }
1058
0
    return complex_subtype_from_doubles(type, cr.real, ci.real);
1059
0
}
1060
1061
static PyNumberMethods complex_as_number = {
1062
    (binaryfunc)complex_add,                    /* nb_add */
1063
    (binaryfunc)complex_sub,                    /* nb_subtract */
1064
    (binaryfunc)complex_mul,                    /* nb_multiply */
1065
    (binaryfunc)complex_remainder,              /* nb_remainder */
1066
    (binaryfunc)complex_divmod,                 /* nb_divmod */
1067
    (ternaryfunc)complex_pow,                   /* nb_power */
1068
    (unaryfunc)complex_neg,                     /* nb_negative */
1069
    (unaryfunc)complex_pos,                     /* nb_positive */
1070
    (unaryfunc)complex_abs,                     /* nb_absolute */
1071
    (inquiry)complex_bool,                      /* nb_bool */
1072
    0,                                          /* nb_invert */
1073
    0,                                          /* nb_lshift */
1074
    0,                                          /* nb_rshift */
1075
    0,                                          /* nb_and */
1076
    0,                                          /* nb_xor */
1077
    0,                                          /* nb_or */
1078
    complex_int,                                /* nb_int */
1079
    0,                                          /* nb_reserved */
1080
    complex_float,                              /* nb_float */
1081
    0,                                          /* nb_inplace_add */
1082
    0,                                          /* nb_inplace_subtract */
1083
    0,                                          /* nb_inplace_multiply*/
1084
    0,                                          /* nb_inplace_remainder */
1085
    0,                                          /* nb_inplace_power */
1086
    0,                                          /* nb_inplace_lshift */
1087
    0,                                          /* nb_inplace_rshift */
1088
    0,                                          /* nb_inplace_and */
1089
    0,                                          /* nb_inplace_xor */
1090
    0,                                          /* nb_inplace_or */
1091
    (binaryfunc)complex_int_div,                /* nb_floor_divide */
1092
    (binaryfunc)complex_div,                    /* nb_true_divide */
1093
    0,                                          /* nb_inplace_floor_divide */
1094
    0,                                          /* nb_inplace_true_divide */
1095
};
1096
1097
PyTypeObject PyComplex_Type = {
1098
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
1099
    "complex",
1100
    sizeof(PyComplexObject),
1101
    0,
1102
    0,                                          /* tp_dealloc */
1103
    0,                                          /* tp_vectorcall_offset */
1104
    0,                                          /* tp_getattr */
1105
    0,                                          /* tp_setattr */
1106
    0,                                          /* tp_as_async */
1107
    (reprfunc)complex_repr,                     /* tp_repr */
1108
    &complex_as_number,                         /* tp_as_number */
1109
    0,                                          /* tp_as_sequence */
1110
    0,                                          /* tp_as_mapping */
1111
    (hashfunc)complex_hash,                     /* tp_hash */
1112
    0,                                          /* tp_call */
1113
    0,                                          /* tp_str */
1114
    PyObject_GenericGetAttr,                    /* tp_getattro */
1115
    0,                                          /* tp_setattro */
1116
    0,                                          /* tp_as_buffer */
1117
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,   /* tp_flags */
1118
    complex_new__doc__,                         /* tp_doc */
1119
    0,                                          /* tp_traverse */
1120
    0,                                          /* tp_clear */
1121
    complex_richcompare,                        /* tp_richcompare */
1122
    0,                                          /* tp_weaklistoffset */
1123
    0,                                          /* tp_iter */
1124
    0,                                          /* tp_iternext */
1125
    complex_methods,                            /* tp_methods */
1126
    complex_members,                            /* tp_members */
1127
    0,                                          /* tp_getset */
1128
    0,                                          /* tp_base */
1129
    0,                                          /* tp_dict */
1130
    0,                                          /* tp_descr_get */
1131
    0,                                          /* tp_descr_set */
1132
    0,                                          /* tp_dictoffset */
1133
    0,                                          /* tp_init */
1134
    PyType_GenericAlloc,                        /* tp_alloc */
1135
    complex_new,                                /* tp_new */
1136
    PyObject_Del,                               /* tp_free */
1137
};