Coverage Report

Created: 2026-12-01 06:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Objects/complexobject.c
Line
Count
Source
1
/* Complex object implementation */
2
3
/* Borrows heavily from floatobject.c */
4
5
/* Submitted by Jim Hugunin */
6
7
#include "Python.h"
8
#include "pycore_call.h"          // _PyObject_CallNoArgs()
9
#include "pycore_complexobject.h" // _PyComplex_FormatAdvancedWriter()
10
#include "pycore_floatobject.h"   // _Py_convert_int_to_double()
11
#include "pycore_freelist.h"      // _Py_FREELIST_FREE(), _Py_FREELIST_POP()
12
#include "pycore_long.h"          // _PyLong_GetZero()
13
#include "pycore_object.h"        // _PyObject_Init()
14
#include "pycore_pymath.h"        // _Py_ADJUST_ERANGE2()
15
16
17
2.09k
#define _PyComplexObject_CAST(op)   ((PyComplexObject *)(op))
18
19
20
/*[clinic input]
21
class complex "PyComplexObject *" "&PyComplex_Type"
22
[clinic start generated code]*/
23
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=819e057d2d10f5ec]*/
24
25
#include "clinic/complexobject.c.h"
26
27
/* elementary operations on complex numbers */
28
29
Py_complex
30
_Py_c_sum(Py_complex a, Py_complex b)
31
0
{
32
0
    Py_complex r;
33
0
    r.real = a.real + b.real;
34
0
    r.imag = a.imag + b.imag;
35
0
    return r;
36
0
}
37
38
Py_complex
39
_Py_cr_sum(Py_complex a, double b)
40
0
{
41
0
    Py_complex r = a;
42
0
    r.real += b;
43
0
    return r;
44
0
}
45
46
static inline Py_complex
47
_Py_rc_sum(double a, Py_complex b)
48
0
{
49
0
    return _Py_cr_sum(b, a);
50
0
}
51
52
Py_complex
53
_Py_c_diff(Py_complex a, Py_complex b)
54
0
{
55
0
    Py_complex r;
56
0
    r.real = a.real - b.real;
57
0
    r.imag = a.imag - b.imag;
58
0
    return r;
59
0
}
60
61
Py_complex
62
_Py_cr_diff(Py_complex a, double b)
63
0
{
64
0
    Py_complex r = a;
65
0
    r.real -= b;
66
0
    return r;
67
0
}
68
69
Py_complex
70
_Py_rc_diff(double a, Py_complex b)
71
0
{
72
0
    Py_complex r;
73
0
    r.real = a - b.real;
74
0
    r.imag = -b.imag;
75
0
    return r;
76
0
}
77
78
Py_complex
79
_Py_c_neg(Py_complex a)
80
0
{
81
0
    Py_complex r;
82
0
    r.real = -a.real;
83
0
    r.imag = -a.imag;
84
0
    return r;
85
0
}
86
87
Py_complex
88
_Py_c_prod(Py_complex z, Py_complex w)
89
0
{
90
0
    double a = z.real, b = z.imag, c = w.real, d = w.imag;
91
0
    double ac = a*c, bd = b*d, ad = a*d, bc = b*c;
92
0
    Py_complex r = {ac - bd, ad + bc};
93
94
    /* Recover infinities that computed as nan+nanj.  See e.g. the C11,
95
       Annex G.5.1, routine _Cmultd(). */
96
0
    if (isnan(r.real) && isnan(r.imag)) {
97
0
        int recalc = 0;
98
99
0
        if (isinf(a) || isinf(b)) {  /* z is infinite */
100
            /* "Box" the infinity and change nans in the other factor to 0 */
101
0
            a = copysign(isinf(a) ? 1.0 : 0.0, a);
102
0
            b = copysign(isinf(b) ? 1.0 : 0.0, b);
103
0
            if (isnan(c)) {
104
0
                c = copysign(0.0, c);
105
0
            }
106
0
            if (isnan(d)) {
107
0
                d = copysign(0.0, d);
108
0
            }
109
0
            recalc = 1;
110
0
        }
111
0
        if (isinf(c) || isinf(d)) {  /* w is infinite */
112
            /* "Box" the infinity and change nans in the other factor to 0 */
113
0
            c = copysign(isinf(c) ? 1.0 : 0.0, c);
114
0
            d = copysign(isinf(d) ? 1.0 : 0.0, d);
115
0
            if (isnan(a)) {
116
0
                a = copysign(0.0, a);
117
0
            }
118
0
            if (isnan(b)) {
119
0
                b = copysign(0.0, b);
120
0
            }
121
0
            recalc = 1;
122
0
        }
123
0
        if (!recalc && (isinf(ac) || isinf(bd) || isinf(ad) || isinf(bc))) {
124
            /* Recover infinities from overflow by changing nans to 0 */
125
0
            if (isnan(a)) {
126
0
                a = copysign(0.0, a);
127
0
            }
128
0
            if (isnan(b)) {
129
0
                b = copysign(0.0, b);
130
0
            }
131
0
            if (isnan(c)) {
132
0
                c = copysign(0.0, c);
133
0
            }
134
0
            if (isnan(d)) {
135
0
                d = copysign(0.0, d);
136
0
            }
137
0
            recalc = 1;
138
0
        }
139
0
        if (recalc) {
140
0
            r.real = INFINITY*(a*c - b*d);
141
0
            r.imag = INFINITY*(a*d + b*c);
142
0
        }
143
0
    }
144
145
0
    return r;
146
0
}
147
148
Py_complex
149
_Py_cr_prod(Py_complex a, double b)
150
0
{
151
0
    Py_complex r = a;
152
0
    r.real *= b;
153
0
    r.imag *= b;
154
0
    return r;
155
0
}
156
157
static inline Py_complex
158
_Py_rc_prod(double a, Py_complex b)
159
0
{
160
0
    return _Py_cr_prod(b, a);
161
0
}
162
163
/* Avoid bad optimization on Windows ARM64 until the compiler is fixed */
164
#ifdef _M_ARM64
165
#pragma optimize("", off)
166
#endif
167
Py_complex
168
_Py_c_quot(Py_complex a, Py_complex b)
169
0
{
170
    /******************************************************************
171
    This was the original algorithm.  It's grossly prone to spurious
172
    overflow and underflow errors.  It also merrily divides by 0 despite
173
    checking for that(!).  The code still serves a doc purpose here, as
174
    the algorithm following is a simple by-cases transformation of this
175
    one:
176
177
    Py_complex r;
178
    double d = b.real*b.real + b.imag*b.imag;
179
    if (d == 0.)
180
        errno = EDOM;
181
    r.real = (a.real*b.real + a.imag*b.imag)/d;
182
    r.imag = (a.imag*b.real - a.real*b.imag)/d;
183
    return r;
184
    ******************************************************************/
185
186
    /* This algorithm is better, and is pretty obvious:  first divide the
187
     * numerators and denominator by whichever of {b.real, b.imag} has
188
     * larger magnitude.  The earliest reference I found was to CACM
189
     * Algorithm 116 (Complex Division, Robert L. Smith, Stanford
190
     * University).
191
     */
192
0
     Py_complex r;      /* the result */
193
0
     const double abs_breal = b.real < 0 ? -b.real : b.real;
194
0
     const double abs_bimag = b.imag < 0 ? -b.imag : b.imag;
195
196
0
    if (abs_breal >= abs_bimag) {
197
        /* divide tops and bottom by b.real */
198
0
        if (abs_breal == 0.0) {
199
0
            errno = EDOM;
200
0
            r.real = r.imag = 0.0;
201
0
        }
202
0
        else {
203
0
            const double ratio = b.imag / b.real;
204
0
            const double denom = b.real + b.imag * ratio;
205
0
            r.real = (a.real + a.imag * ratio) / denom;
206
0
            r.imag = (a.imag - a.real * ratio) / denom;
207
0
        }
208
0
    }
209
0
    else if (abs_bimag >= abs_breal) {
210
        /* divide tops and bottom by b.imag */
211
0
        const double ratio = b.real / b.imag;
212
0
        const double denom = b.real * ratio + b.imag;
213
0
        assert(b.imag != 0.0);
214
0
        r.real = (a.real * ratio + a.imag) / denom;
215
0
        r.imag = (a.imag * ratio - a.real) / denom;
216
0
    }
217
0
    else {
218
        /* At least one of b.real or b.imag is a NaN */
219
0
        r.real = r.imag = Py_NAN;
220
0
    }
221
222
    /* Recover infinities and zeros that computed as nan+nanj.  See e.g.
223
       the C11, Annex G.5.2, routine _Cdivd(). */
224
0
    if (isnan(r.real) && isnan(r.imag)) {
225
0
        if ((isinf(a.real) || isinf(a.imag))
226
0
            && isfinite(b.real) && isfinite(b.imag))
227
0
        {
228
0
            const double x = copysign(isinf(a.real) ? 1.0 : 0.0, a.real);
229
0
            const double y = copysign(isinf(a.imag) ? 1.0 : 0.0, a.imag);
230
0
            r.real = INFINITY * (x*b.real + y*b.imag);
231
0
            r.imag = INFINITY * (y*b.real - x*b.imag);
232
0
        }
233
0
        else if ((isinf(abs_breal) || isinf(abs_bimag))
234
0
                 && isfinite(a.real) && isfinite(a.imag))
235
0
        {
236
0
            const double x = copysign(isinf(b.real) ? 1.0 : 0.0, b.real);
237
0
            const double y = copysign(isinf(b.imag) ? 1.0 : 0.0, b.imag);
238
0
            r.real = 0.0 * (a.real*x + a.imag*y);
239
0
            r.imag = 0.0 * (a.imag*x - a.real*y);
240
0
        }
241
0
    }
242
243
0
    return r;
244
0
}
245
246
Py_complex
247
_Py_cr_quot(Py_complex a, double b)
248
0
{
249
0
    Py_complex r = a;
250
0
    if (b) {
251
0
        r.real /= b;
252
0
        r.imag /= b;
253
0
    }
254
0
    else {
255
0
        errno = EDOM;
256
0
        r.real = r.imag = 0.0;
257
0
    }
258
0
    return r;
259
0
}
260
261
/* an equivalent of _Py_c_quot() function, when 1st argument is real */
262
Py_complex
263
_Py_rc_quot(double a, Py_complex b)
264
0
{
265
0
    Py_complex r;
266
0
    const double abs_breal = b.real < 0 ? -b.real : b.real;
267
0
    const double abs_bimag = b.imag < 0 ? -b.imag : b.imag;
268
269
0
    if (abs_breal >= abs_bimag) {
270
0
        if (abs_breal == 0.0) {
271
0
            errno = EDOM;
272
0
            r.real = r.imag = 0.0;
273
0
        }
274
0
        else {
275
0
            const double ratio = b.imag / b.real;
276
0
            const double denom = b.real + b.imag * ratio;
277
0
            r.real = a / denom;
278
0
            r.imag = (-a * ratio) / denom;
279
0
        }
280
0
    }
281
0
    else if (abs_bimag >= abs_breal) {
282
0
        const double ratio = b.real / b.imag;
283
0
        const double denom = b.real * ratio + b.imag;
284
0
        assert(b.imag != 0.0);
285
0
        r.real = (a * ratio) / denom;
286
0
        r.imag = (-a) / denom;
287
0
    }
288
0
    else {
289
0
        r.real = r.imag = Py_NAN;
290
0
    }
291
292
0
    if (isnan(r.real) && isnan(r.imag) && isfinite(a)
293
0
        && (isinf(abs_breal) || isinf(abs_bimag)))
294
0
    {
295
0
        const double x = copysign(isinf(b.real) ? 1.0 : 0.0, b.real);
296
0
        const double y = copysign(isinf(b.imag) ? 1.0 : 0.0, b.imag);
297
0
        r.real = 0.0 * (a*x);
298
0
        r.imag = 0.0 * (-a*y);
299
0
    }
300
301
0
    return r;
302
0
}
303
#ifdef _M_ARM64
304
#pragma optimize("", on)
305
#endif
306
307
Py_complex
308
_Py_c_pow(Py_complex a, Py_complex b)
309
0
{
310
0
    Py_complex r;
311
0
    double vabs,len,at,phase;
312
0
    if (b.real == 0. && b.imag == 0.) {
313
0
        r.real = 1.;
314
0
        r.imag = 0.;
315
0
    }
316
0
    else if (a.real == 0. && a.imag == 0.) {
317
0
        if (b.imag != 0. || b.real < 0.)
318
0
            errno = EDOM;
319
0
        r.real = 0.;
320
0
        r.imag = 0.;
321
0
    }
322
0
    else {
323
0
        vabs = hypot(a.real,a.imag);
324
0
        len = pow(vabs,b.real);
325
0
        at = atan2(a.imag, a.real);
326
0
        phase = at*b.real;
327
0
        if (b.imag != 0.0) {
328
0
            len *= exp(-at*b.imag);
329
0
            phase += b.imag*log(vabs);
330
0
        }
331
0
        r.real = len*cos(phase);
332
0
        r.imag = len*sin(phase);
333
334
        /* Don't rely on errno set by the math functions above, for
335
           example cos() and sin() set EDOM for an infinite phase. */
336
0
        errno = 0;
337
0
        if (isfinite(a.real) && isfinite(a.imag)
338
0
            && isfinite(b.real) && isfinite(b.imag))
339
0
        {
340
0
            _Py_ADJUST_ERANGE2(r.real, r.imag);
341
0
        }
342
0
    }
343
0
    return r;
344
0
}
345
346
0
#define INT_EXP_CUTOFF 100
347
348
static Py_complex
349
c_powu(Py_complex x, long n)
350
0
{
351
0
    assert(0 < n && n <= INT_EXP_CUTOFF);
352
0
    while ((n & 1) == 0) {
353
0
        x = _Py_c_prod(x, x);
354
0
        n >>= 1;
355
0
    }
356
0
    Py_complex r = x;
357
0
    n >>= 1;
358
0
    while (n) {
359
0
        x = _Py_c_prod(x, x);
360
0
        if (n & 1) {
361
0
            r = _Py_c_prod(r, x);
362
0
        }
363
0
        n >>= 1;
364
0
    }
365
0
    return r;
366
0
}
367
368
static Py_complex
369
c_powi(Py_complex x, long n)
370
0
{
371
0
    if (n > 0)
372
0
        return c_powu(x, n);
373
0
    else if (n < 0)
374
0
        return _Py_rc_quot(1.0, c_powu(x, -n));
375
0
    else
376
0
        return (Py_complex){1., 0.};
377
0
}
378
379
double
380
_Py_c_abs(Py_complex z)
381
0
{
382
    /* sets errno = ERANGE on overflow */
383
0
    double result;
384
0
    int saved_errno = errno;
385
386
0
    if (!isfinite(z.real) || !isfinite(z.imag)) {
387
        /* C99 rules: if either the real or the imaginary part is an
388
           infinity, return infinity, even if the other part is a
389
           NaN. */
390
0
        if (isinf(z.real)) {
391
0
            result = fabs(z.real);
392
0
            errno = saved_errno;
393
0
            return result;
394
0
        }
395
0
        if (isinf(z.imag)) {
396
0
            result = fabs(z.imag);
397
0
            errno = saved_errno;
398
0
            return result;
399
0
        }
400
        /* either the real or imaginary part is a NaN,
401
           and neither is infinite. Result should be NaN. */
402
0
        errno = saved_errno;
403
0
        return Py_NAN;
404
0
    }
405
0
    result = hypot(z.real, z.imag);
406
0
    if (!isfinite(result))
407
0
        errno = ERANGE;
408
0
    else
409
0
        errno = saved_errno;
410
0
    return result;
411
0
}
412
413
static PyObject *
414
complex_subtype_from_c_complex(PyTypeObject *type, Py_complex cval)
415
0
{
416
0
    PyObject *op;
417
418
0
    if (type == &PyComplex_Type) {
419
0
        return PyComplex_FromCComplex(cval);
420
0
    }
421
0
    op = type->tp_alloc(type, 0);
422
0
    if (op != NULL)
423
0
        ((PyComplexObject *)op)->cval = cval;
424
0
    return op;
425
0
}
426
427
PyObject *
428
PyComplex_FromCComplex(Py_complex cval)
429
7.56k
{
430
7.56k
    PyComplexObject *op = _Py_FREELIST_POP(PyComplexObject, complexes);
431
432
7.56k
    if (op == NULL) {
433
        /* Inline PyObject_New */
434
2.11k
        op = PyObject_Malloc(sizeof(PyComplexObject));
435
2.11k
        if (op == NULL) {
436
0
            return PyErr_NoMemory();
437
0
        }
438
2.11k
        _PyObject_Init((PyObject*)op, &PyComplex_Type);
439
2.11k
    }
440
7.56k
    op->cval = cval;
441
7.56k
    return (PyObject *) op;
442
7.56k
}
443
444
static void
445
complex_dealloc(PyObject *op)
446
7.56k
{
447
7.56k
    assert(PyComplex_Check(op));
448
7.56k
    if (PyComplex_CheckExact(op)) {
449
7.56k
        _Py_FREELIST_FREE(complexes, op, PyObject_Free);
450
7.56k
    }
451
0
    else {
452
0
        Py_TYPE(op)->tp_free(op);
453
0
    }
454
7.56k
}
455
456
static PyObject *
457
complex_subtype_from_doubles(PyTypeObject *type, double real, double imag)
458
0
{
459
0
    Py_complex c;
460
0
    c.real = real;
461
0
    c.imag = imag;
462
0
    return complex_subtype_from_c_complex(type, c);
463
0
}
464
465
PyObject *
466
PyComplex_FromDoubles(double real, double imag)
467
0
{
468
0
    Py_complex c;
469
0
    c.real = real;
470
0
    c.imag = imag;
471
0
    return PyComplex_FromCComplex(c);
472
0
}
473
474
static PyObject * try_complex_special_method(PyObject *);
475
476
double
477
PyComplex_RealAsDouble(PyObject *op)
478
0
{
479
0
    double real = -1.0;
480
481
0
    if (PyComplex_Check(op)) {
482
0
        real = ((PyComplexObject *)op)->cval.real;
483
0
    }
484
0
    else {
485
0
        PyObject* newop = try_complex_special_method(op);
486
0
        if (newop) {
487
0
            real = ((PyComplexObject *)newop)->cval.real;
488
0
            Py_DECREF(newop);
489
0
        } else if (!PyErr_Occurred()) {
490
0
            real = PyFloat_AsDouble(op);
491
0
        }
492
0
    }
493
494
0
    return real;
495
0
}
496
497
double
498
PyComplex_ImagAsDouble(PyObject *op)
499
0
{
500
0
    double imag = -1.0;
501
502
0
    if (PyComplex_Check(op)) {
503
0
        imag = ((PyComplexObject *)op)->cval.imag;
504
0
    }
505
0
    else {
506
0
        PyObject* newop = try_complex_special_method(op);
507
0
        if (newop) {
508
0
            imag = ((PyComplexObject *)newop)->cval.imag;
509
0
            Py_DECREF(newop);
510
0
        } else if (!PyErr_Occurred()) {
511
0
            PyFloat_AsDouble(op);
512
0
            if (!PyErr_Occurred()) {
513
0
                imag = 0.0;
514
0
            }
515
0
        }
516
0
    }
517
518
0
    return imag;
519
0
}
520
521
static PyObject *
522
try_complex_special_method(PyObject *op)
523
0
{
524
0
    PyObject *f;
525
526
0
    f = _PyObject_LookupSpecial(op, &_Py_ID(__complex__));
527
0
    if (f) {
528
0
        PyObject *res = _PyObject_CallNoArgs(f);
529
0
        Py_DECREF(f);
530
0
        if (!res || PyComplex_CheckExact(res)) {
531
0
            return res;
532
0
        }
533
0
        if (!PyComplex_Check(res)) {
534
0
            PyErr_Format(PyExc_TypeError,
535
0
                "%T.__complex__() must return a complex, not %T",
536
0
                op, res);
537
0
            Py_DECREF(res);
538
0
            return NULL;
539
0
        }
540
        /* Issue #29894: warn if 'res' not of exact type complex. */
541
0
        if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
542
0
                "%T.__complex__() must return a complex, not %T.  "
543
0
                "The ability to return an instance of a strict subclass of complex "
544
0
                "is deprecated, and may be removed in a future version of Python.",
545
0
                op, res)) {
546
0
            Py_DECREF(res);
547
0
            return NULL;
548
0
        }
549
0
        return res;
550
0
    }
551
0
    return NULL;
552
0
}
553
554
Py_complex
555
PyComplex_AsCComplex(PyObject *op)
556
0
{
557
0
    Py_complex cv;
558
0
    PyObject *newop = NULL;
559
560
0
    assert(op);
561
    /* If op is already of type PyComplex_Type, return its value */
562
0
    if (PyComplex_Check(op)) {
563
0
        return ((PyComplexObject *)op)->cval;
564
0
    }
565
    /* If not, use op's __complex__  method, if it exists */
566
567
    /* return -1 on failure */
568
0
    cv.real = -1.;
569
0
    cv.imag = 0.;
570
571
0
    newop = try_complex_special_method(op);
572
573
0
    if (newop) {
574
0
        cv = ((PyComplexObject *)newop)->cval;
575
0
        Py_DECREF(newop);
576
0
        return cv;
577
0
    }
578
0
    else if (PyErr_Occurred()) {
579
0
        return cv;
580
0
    }
581
    /* If neither of the above works, interpret op as a float giving the
582
       real part of the result, and fill in the imaginary part as 0. */
583
0
    else {
584
        /* PyFloat_AsDouble will return -1 on failure */
585
0
        cv.real = PyFloat_AsDouble(op);
586
0
        return cv;
587
0
    }
588
0
}
589
590
static PyObject *
591
complex_repr(PyObject *op)
592
2.09k
{
593
2.09k
    int precision = 0;
594
2.09k
    char format_code = 'r';
595
2.09k
    PyObject *result = NULL;
596
2.09k
    PyComplexObject *v = _PyComplexObject_CAST(op);
597
598
    /* If these are non-NULL, they'll need to be freed. */
599
2.09k
    char *pre = NULL;
600
2.09k
    char *im = NULL;
601
602
    /* These do not need to be freed. re is either an alias
603
       for pre or a pointer to a constant.  lead and tail
604
       are pointers to constants. */
605
2.09k
    const char *re = NULL;
606
2.09k
    const char *lead = "";
607
2.09k
    const char *tail = "";
608
609
2.09k
    if (v->cval.real == 0. && copysign(1.0, v->cval.real)==1.0) {
610
        /* Real part is +0: just output the imaginary part and do not
611
           include parens. */
612
2.09k
        re = "";
613
2.09k
        im = PyOS_double_to_string(v->cval.imag, format_code,
614
2.09k
                                   precision, 0, NULL);
615
2.09k
        if (!im) {
616
0
            PyErr_NoMemory();
617
0
            goto done;
618
0
        }
619
2.09k
    } else {
620
        /* Format imaginary part with sign, real part without. Include
621
           parens in the result. */
622
0
        pre = PyOS_double_to_string(v->cval.real, format_code,
623
0
                                    precision, 0, NULL);
624
0
        if (!pre) {
625
0
            PyErr_NoMemory();
626
0
            goto done;
627
0
        }
628
0
        re = pre;
629
630
0
        im = PyOS_double_to_string(v->cval.imag, format_code,
631
0
                                   precision, Py_DTSF_SIGN, NULL);
632
0
        if (!im) {
633
0
            PyErr_NoMemory();
634
0
            goto done;
635
0
        }
636
0
        lead = "(";
637
0
        tail = ")";
638
0
    }
639
2.09k
    result = PyUnicode_FromFormat("%s%s%sj%s", lead, re, im, tail);
640
2.09k
  done:
641
2.09k
    PyMem_Free(im);
642
2.09k
    PyMem_Free(pre);
643
644
2.09k
    return result;
645
2.09k
}
646
647
static Py_hash_t
648
complex_hash(PyObject *op)
649
0
{
650
0
    Py_uhash_t hashreal, hashimag, combined;
651
0
    PyComplexObject *v = _PyComplexObject_CAST(op);
652
0
    hashreal = (Py_uhash_t)_Py_HashDouble(op, v->cval.real);
653
0
    if (hashreal == (Py_uhash_t)-1)
654
0
        return -1;
655
0
    hashimag = (Py_uhash_t)_Py_HashDouble(op, v->cval.imag);
656
0
    if (hashimag == (Py_uhash_t)-1)
657
0
        return -1;
658
    /* Note:  if the imaginary part is 0, hashimag is 0 now,
659
     * so the following returns hashreal unchanged.  This is
660
     * important because numbers of different types that
661
     * compare equal must have the same hash value, so that
662
     * hash(x + 0*j) must equal hash(x).
663
     */
664
0
    combined = hashreal + PyHASH_IMAG * hashimag;
665
0
    if (combined == (Py_uhash_t)-1)
666
0
        combined = (Py_uhash_t)-2;
667
0
    return (Py_hash_t)combined;
668
0
}
669
670
/* This macro may return! */
671
#define TO_COMPLEX(obj, c)                      \
672
0
    if (PyComplex_Check(obj))                   \
673
0
        c = ((PyComplexObject *)(obj))->cval;   \
674
0
    else if (real_to_complex(&(obj), &(c)) < 0) \
675
0
        return (obj)
676
677
static int
678
real_to_double(PyObject **pobj, double *dbl)
679
0
{
680
0
    PyObject *obj = *pobj;
681
682
0
    if (PyFloat_Check(obj)) {
683
0
        *dbl = PyFloat_AS_DOUBLE(obj);
684
0
    }
685
0
    else if (_Py_convert_int_to_double(pobj, dbl) < 0) {
686
0
        return -1;
687
0
    }
688
0
    return 0;
689
0
}
690
691
static int
692
real_to_complex(PyObject **pobj, Py_complex *pc)
693
0
{
694
0
    pc->imag = 0.0;
695
0
    return real_to_double(pobj, &(pc->real));
696
0
}
697
698
/* Complex arithmetic rules implement special mixed-mode case where combining
699
   a pure-real (float or int) value and a complex value is performed directly
700
   without first coercing the real value to a complex value.
701
702
   Let us consider the addition as an example, assuming that ints are implicitly
703
   converted to floats.  We have the following rules (up to variants with changed
704
   order of operands):
705
706
       complex(a, b) + complex(c, d) = complex(a + c, b + d)
707
       float(a) + complex(b, c) = complex(a + b, c)
708
709
   Similar rules are implemented for subtraction, multiplication and division.
710
   See C11's Annex G, sections G.5.1 and G.5.2.
711
 */
712
713
#define COMPLEX_BINOP(NAME, FUNC)                           \
714
    static PyObject *                                       \
715
    complex_##NAME(PyObject *v, PyObject *w)                \
716
0
    {                                                       \
717
0
        Py_complex a;                                       \
718
0
        errno = 0;                                          \
719
0
        if (PyComplex_Check(w)) {                           \
720
0
            Py_complex b = ((PyComplexObject *)w)->cval;    \
721
0
            if (PyComplex_Check(v)) {                       \
722
0
                a = ((PyComplexObject *)v)->cval;           \
723
0
                a = _Py_c_##FUNC(a, b);                     \
724
0
            }                                               \
725
0
            else if (real_to_double(&v, &a.real) < 0) {     \
726
0
                return v;                                   \
727
0
            }                                               \
728
0
            else {                                          \
729
0
                a = _Py_rc_##FUNC(a.real, b);               \
730
0
            }                                               \
731
0
        }                                                   \
732
0
        else if (!PyComplex_Check(v)) {                     \
733
0
            Py_RETURN_NOTIMPLEMENTED;                       \
734
0
        }                                                   \
735
0
        else {                                              \
736
0
            a = ((PyComplexObject *)v)->cval;               \
737
0
            double b;                                       \
738
0
            if (real_to_double(&w, &b) < 0) {               \
739
0
                return w;                                   \
740
0
            }                                               \
741
0
            a = _Py_cr_##FUNC(a, b);                        \
742
0
        }                                                   \
743
0
        if (errno == EDOM) {                                \
744
0
            PyErr_SetString(PyExc_ZeroDivisionError,        \
745
0
                            "division by zero");            \
746
0
            return NULL;                                    \
747
0
        }                                                   \
748
0
        return PyComplex_FromCComplex(a);                   \
749
0
   }
750
751
0
COMPLEX_BINOP(add, sum)
752
0
COMPLEX_BINOP(mul, prod)
753
0
COMPLEX_BINOP(sub, diff)
754
0
COMPLEX_BINOP(div, quot)
755
756
static PyObject *
757
complex_pow(PyObject *v, PyObject *w, PyObject *z)
758
0
{
759
0
    Py_complex p;
760
0
    Py_complex a, b;
761
0
    TO_COMPLEX(v, a);
762
0
    TO_COMPLEX(w, b);
763
764
0
    if (z != Py_None) {
765
0
        PyErr_SetString(PyExc_ValueError, "complex modulo");
766
0
        return NULL;
767
0
    }
768
0
    errno = 0;
769
    // Check whether the exponent has a small integer value, and if so use
770
    // a faster and more accurate algorithm.
771
0
    if (b.imag == 0.0 && b.real == floor(b.real)
772
0
        && fabs(b.real) <= INT_EXP_CUTOFF)
773
0
    {
774
0
        p = c_powi(a, (long)b.real);
775
0
        if (isfinite(a.real) && isfinite(a.imag)) {
776
0
            _Py_ADJUST_ERANGE2(p.real, p.imag);
777
0
        }
778
0
    }
779
0
    else {
780
0
        p = _Py_c_pow(a, b);
781
0
    }
782
783
0
    if (errno == EDOM) {
784
0
        PyErr_SetString(PyExc_ZeroDivisionError,
785
0
                        "zero to a negative or complex power");
786
0
        return NULL;
787
0
    }
788
0
    else if (errno == ERANGE) {
789
0
        PyErr_SetString(PyExc_OverflowError,
790
0
                        "complex exponentiation");
791
0
        return NULL;
792
0
    }
793
0
    return PyComplex_FromCComplex(p);
794
0
}
795
796
static PyObject *
797
complex_neg(PyObject *op)
798
0
{
799
0
    PyComplexObject *v = _PyComplexObject_CAST(op);
800
0
    Py_complex neg;
801
0
    neg.real = -v->cval.real;
802
0
    neg.imag = -v->cval.imag;
803
0
    return PyComplex_FromCComplex(neg);
804
0
}
805
806
static PyObject *
807
complex_pos(PyObject *op)
808
0
{
809
0
    PyComplexObject *v = _PyComplexObject_CAST(op);
810
0
    if (PyComplex_CheckExact(v)) {
811
0
        return Py_NewRef(v);
812
0
    }
813
0
    return PyComplex_FromCComplex(v->cval);
814
0
}
815
816
static PyObject *
817
complex_abs(PyObject *op)
818
0
{
819
0
    PyComplexObject *v = _PyComplexObject_CAST(op);
820
0
    double result;
821
822
0
    errno = 0;
823
0
    result = _Py_c_abs(v->cval);
824
0
    if (errno == ERANGE) {
825
0
        PyErr_SetString(PyExc_OverflowError,
826
0
                        "absolute value too large");
827
0
        return NULL;
828
0
    }
829
0
    return PyFloat_FromDouble(result);
830
0
}
831
832
static int
833
complex_bool(PyObject *op)
834
0
{
835
0
    PyComplexObject *v = _PyComplexObject_CAST(op);
836
0
    return v->cval.real != 0.0 || v->cval.imag != 0.0;
837
0
}
838
839
static PyObject *
840
complex_richcompare(PyObject *v, PyObject *w, int op)
841
0
{
842
0
    PyObject *res;
843
0
    Py_complex i;
844
0
    int equal;
845
846
0
    if (op != Py_EQ && op != Py_NE) {
847
0
        goto Unimplemented;
848
0
    }
849
850
0
    assert(PyComplex_Check(v));
851
0
    TO_COMPLEX(v, i);
852
853
0
    if (PyLong_Check(w)) {
854
        /* Check for 0.0 imaginary part first to avoid the rich
855
         * comparison when possible.
856
         */
857
0
        if (i.imag == 0.0) {
858
0
            PyObject *j, *sub_res;
859
0
            j = PyFloat_FromDouble(i.real);
860
0
            if (j == NULL)
861
0
                return NULL;
862
863
0
            sub_res = PyObject_RichCompare(j, w, op);
864
0
            Py_DECREF(j);
865
0
            return sub_res;
866
0
        }
867
0
        else {
868
0
            equal = 0;
869
0
        }
870
0
    }
871
0
    else if (PyFloat_Check(w)) {
872
0
        equal = (i.real == PyFloat_AsDouble(w) && i.imag == 0.0);
873
0
    }
874
0
    else if (PyComplex_Check(w)) {
875
0
        Py_complex j;
876
877
0
        TO_COMPLEX(w, j);
878
0
        equal = (i.real == j.real && i.imag == j.imag);
879
0
    }
880
0
    else {
881
0
        goto Unimplemented;
882
0
    }
883
884
0
    if (equal == (op == Py_EQ))
885
0
         res = Py_True;
886
0
    else
887
0
         res = Py_False;
888
889
0
    return Py_NewRef(res);
890
891
0
Unimplemented:
892
0
    Py_RETURN_NOTIMPLEMENTED;
893
0
}
894
895
/*[clinic input]
896
@permit_long_summary
897
complex.conjugate
898
899
Return the complex conjugate of its argument. (3-4j).conjugate() == 3+4j.
900
[clinic start generated code]*/
901
902
static PyObject *
903
complex_conjugate_impl(PyComplexObject *self)
904
/*[clinic end generated code: output=5059ef162edfc68e input=71b8ab003e1cec95]*/
905
0
{
906
0
    Py_complex c = self->cval;
907
0
    c.imag = -c.imag;
908
0
    return PyComplex_FromCComplex(c);
909
0
}
910
911
/*[clinic input]
912
complex.__getnewargs__
913
914
[clinic start generated code]*/
915
916
static PyObject *
917
complex___getnewargs___impl(PyComplexObject *self)
918
/*[clinic end generated code: output=689b8206e8728934 input=539543e0a50533d7]*/
919
0
{
920
0
    Py_complex c = self->cval;
921
0
    return Py_BuildValue("(dd)", c.real, c.imag);
922
0
}
923
924
925
/*[clinic input]
926
complex.__format__
927
928
    format_spec: unicode
929
    /
930
931
Convert to a string according to format_spec.
932
[clinic start generated code]*/
933
934
static PyObject *
935
complex___format___impl(PyComplexObject *self, PyObject *format_spec)
936
/*[clinic end generated code: output=bfcb60df24cafea0 input=014ef5488acbe1d5]*/
937
0
{
938
0
    _PyUnicodeWriter writer;
939
0
    int ret;
940
0
    _PyUnicodeWriter_Init(&writer);
941
0
    ret = _PyComplex_FormatAdvancedWriter(
942
0
        &writer,
943
0
        (PyObject *)self,
944
0
        format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
945
0
    if (ret == -1) {
946
0
        _PyUnicodeWriter_Dealloc(&writer);
947
0
        return NULL;
948
0
    }
949
0
    return _PyUnicodeWriter_Finish(&writer);
950
0
}
951
952
/*[clinic input]
953
complex.__complex__
954
955
Convert this value to exact type complex.
956
[clinic start generated code]*/
957
958
static PyObject *
959
complex___complex___impl(PyComplexObject *self)
960
/*[clinic end generated code: output=e6b35ba3d275dc9c input=3589ada9d27db854]*/
961
0
{
962
0
    if (PyComplex_CheckExact(self)) {
963
0
        return Py_NewRef(self);
964
0
    }
965
0
    else {
966
0
        return PyComplex_FromCComplex(self->cval);
967
0
    }
968
0
}
969
970
971
static PyObject *
972
complex_from_string_inner(const char *s, Py_ssize_t len, void *type)
973
0
{
974
0
    double x=0.0, y=0.0, z;
975
0
    int got_bracket=0;
976
0
    const char *start;
977
0
    char *end;
978
979
    /* position on first nonblank */
980
0
    start = s;
981
0
    while (Py_ISSPACE(*s))
982
0
        s++;
983
0
    if (*s == '(') {
984
        /* Skip over possible bracket from repr(). */
985
0
        got_bracket = 1;
986
0
        s++;
987
0
        while (Py_ISSPACE(*s))
988
0
            s++;
989
0
    }
990
991
    /* a valid complex string usually takes one of the three forms:
992
993
         <float>                  - real part only
994
         <float>j                 - imaginary part only
995
         <float><signed-float>j   - real and imaginary parts
996
997
       where <float> represents any numeric string that's accepted by the
998
       float constructor (including 'nan', 'inf', 'infinity', etc.), and
999
       <signed-float> is any string of the form <float> whose first
1000
       character is '+' or '-'.
1001
1002
       For backwards compatibility, the extra forms
1003
1004
         <float><sign>j
1005
         <sign>j
1006
         j
1007
1008
       are also accepted, though support for these forms may be removed from
1009
       a future version of Python.
1010
    */
1011
1012
    /* first look for forms starting with <float> */
1013
0
    z = PyOS_string_to_double(s, &end, NULL);
1014
0
    if (z == -1.0 && PyErr_Occurred()) {
1015
0
        if (PyErr_ExceptionMatches(PyExc_ValueError))
1016
0
            PyErr_Clear();
1017
0
        else
1018
0
            return NULL;
1019
0
    }
1020
0
    if (end != s) {
1021
        /* all 4 forms starting with <float> land here */
1022
0
        s = end;
1023
0
        if (*s == '+' || *s == '-') {
1024
            /* <float><signed-float>j | <float><sign>j */
1025
0
            x = z;
1026
0
            y = PyOS_string_to_double(s, &end, NULL);
1027
0
            if (y == -1.0 && PyErr_Occurred()) {
1028
0
                if (PyErr_ExceptionMatches(PyExc_ValueError))
1029
0
                    PyErr_Clear();
1030
0
                else
1031
0
                    return NULL;
1032
0
            }
1033
0
            if (end != s)
1034
                /* <float><signed-float>j */
1035
0
                s = end;
1036
0
            else {
1037
                /* <float><sign>j */
1038
0
                y = *s == '+' ? 1.0 : -1.0;
1039
0
                s++;
1040
0
            }
1041
0
            if (!(*s == 'j' || *s == 'J'))
1042
0
                goto parse_error;
1043
0
            s++;
1044
0
        }
1045
0
        else if (*s == 'j' || *s == 'J') {
1046
            /* <float>j */
1047
0
            s++;
1048
0
            y = z;
1049
0
        }
1050
0
        else
1051
            /* <float> */
1052
0
            x = z;
1053
0
    }
1054
0
    else {
1055
        /* not starting with <float>; must be <sign>j or j */
1056
0
        if (*s == '+' || *s == '-') {
1057
            /* <sign>j */
1058
0
            y = *s == '+' ? 1.0 : -1.0;
1059
0
            s++;
1060
0
        }
1061
0
        else
1062
            /* j */
1063
0
            y = 1.0;
1064
0
        if (!(*s == 'j' || *s == 'J'))
1065
0
            goto parse_error;
1066
0
        s++;
1067
0
    }
1068
1069
    /* trailing whitespace and closing bracket */
1070
0
    while (Py_ISSPACE(*s))
1071
0
        s++;
1072
0
    if (got_bracket) {
1073
        /* if there was an opening parenthesis, then the corresponding
1074
           closing parenthesis should be right here */
1075
0
        if (*s != ')')
1076
0
            goto parse_error;
1077
0
        s++;
1078
0
        while (Py_ISSPACE(*s))
1079
0
            s++;
1080
0
    }
1081
1082
    /* we should now be at the end of the string */
1083
0
    if (s-start != len)
1084
0
        goto parse_error;
1085
1086
0
    return complex_subtype_from_doubles(_PyType_CAST(type), x, y);
1087
1088
0
  parse_error:
1089
0
    PyErr_SetString(PyExc_ValueError,
1090
0
                    "complex() arg is a malformed string");
1091
0
    return NULL;
1092
0
}
1093
1094
static PyObject *
1095
complex_subtype_from_string(PyTypeObject *type, PyObject *v)
1096
0
{
1097
0
    const char *s;
1098
0
    PyObject *s_buffer = NULL, *result = NULL;
1099
0
    Py_ssize_t len;
1100
1101
0
    if (PyUnicode_Check(v)) {
1102
0
        s_buffer = _PyUnicode_TransformDecimalAndSpaceToASCII(v);
1103
0
        if (s_buffer == NULL) {
1104
0
            return NULL;
1105
0
        }
1106
0
        assert(PyUnicode_IS_ASCII(s_buffer));
1107
        /* Simply get a pointer to existing ASCII characters. */
1108
0
        s = PyUnicode_AsUTF8AndSize(s_buffer, &len);
1109
0
        assert(s != NULL);
1110
0
    }
1111
0
    else {
1112
0
        PyErr_Format(PyExc_TypeError,
1113
0
            "complex() argument must be a string or a number, not %T",
1114
0
            v);
1115
0
        return NULL;
1116
0
    }
1117
1118
0
    result = _Py_string_to_number_with_underscores(s, len, "complex", v, type,
1119
0
                                                   complex_from_string_inner);
1120
0
    Py_DECREF(s_buffer);
1121
0
    return result;
1122
0
}
1123
1124
/* The constructor should only accept a string as a positional argument,
1125
 * not as by the 'real' keyword.  But Argument Clinic does not allow
1126
 * to distinguish between argument passed positionally and by keyword.
1127
 * So complex_new() declares 'real' and 'imag' twice: as positional-only and
1128
 * as keyword-only parameters.  complex_new_impl() calls complex_from_arg()
1129
 * for one positional argument and handles the remaining cases itself:
1130
 * 'real' and 'imag' arguments.  This separation is well suited for
1131
 * different constructor roles: converting a string or number to a complex
1132
 * number and constructing a complex number from real and imaginary parts.
1133
 */
1134
static PyObject *
1135
complex_from_arg(PyTypeObject *type, PyObject *arg)
1136
0
{
1137
0
    PyObject *res = NULL;
1138
0
    PyNumberMethods *nbr;
1139
1140
    /* Special-case for a single argument when type(arg) is complex. */
1141
0
    if (PyComplex_CheckExact(arg) && type == &PyComplex_Type) {
1142
        /* Note that we can't know whether it's safe to return
1143
           a complex *subclass* instance as-is, hence the restriction
1144
           to exact complexes here.  If either the input or the
1145
           output is a complex subclass, it will be handled below
1146
           as a non-orthogonal vector.  */
1147
0
        return Py_NewRef(arg);
1148
0
    }
1149
0
    if (PyUnicode_Check(arg)) {
1150
0
        return complex_subtype_from_string(type, arg);
1151
0
    }
1152
0
    PyObject *tmp = try_complex_special_method(arg);
1153
0
    if (tmp) {
1154
0
        Py_complex c = ((PyComplexObject*)tmp)->cval;
1155
0
        res = complex_subtype_from_doubles(type, c.real, c.imag);
1156
0
        Py_DECREF(tmp);
1157
0
    }
1158
0
    else if (PyErr_Occurred()) {
1159
0
        return NULL;
1160
0
    }
1161
0
    else if (PyComplex_Check(arg)) {
1162
        /* Note that if arg is of a complex subtype, we're only
1163
           retaining its real & imag parts here, and the return
1164
           value is (properly) of the builtin complex type. */
1165
0
        Py_complex c = ((PyComplexObject*)arg)->cval;
1166
0
        res = complex_subtype_from_doubles(type, c.real, c.imag);
1167
0
    }
1168
0
    else if ((nbr = Py_TYPE(arg)->tp_as_number) != NULL &&
1169
0
             (nbr->nb_float != NULL || nbr->nb_index != NULL))
1170
0
    {
1171
        /* The argument really is entirely real, and contributes
1172
           nothing in the imaginary direction.
1173
           Just treat it as a double. */
1174
0
        double r = PyFloat_AsDouble(arg);
1175
0
        if (r != -1.0 || !PyErr_Occurred()) {
1176
0
            res = complex_subtype_from_doubles(type, r, 0);
1177
0
        }
1178
0
    }
1179
0
    else {
1180
0
        PyErr_Format(PyExc_TypeError,
1181
0
                     "complex() argument must be a string or a number, not %T",
1182
0
                     arg);
1183
0
    }
1184
0
    return res;
1185
0
}
1186
1187
/*[clinic input]
1188
@vectorcall
1189
@classmethod
1190
@text_signature "(real=0, imag=0)"
1191
complex.__new__ as complex_new
1192
    real_pos: object = NULL
1193
    imag_pos: object = NULL
1194
    /
1195
    *
1196
    real as r: object = NULL
1197
    imag as i: object = NULL
1198
1199
Create a complex number from a string or numbers.
1200
1201
If a string is given, parse it as a complex number.
1202
If a single number is given, convert it to a complex number.
1203
If the 'real' or 'imag' arguments are given, create a complex number
1204
with the specified real and imaginary components.
1205
[clinic start generated code]*/
1206
1207
static PyObject *
1208
complex_new_impl(PyTypeObject *type, PyObject *real_pos, PyObject *imag_pos,
1209
                 PyObject *r, PyObject *i)
1210
/*[clinic end generated code: output=fdc6ecf8914112b7 input=09930f0cd44fd3a8]*/
1211
0
{
1212
0
    PyObject *tmp;
1213
0
    PyNumberMethods *nbr, *nbi = NULL;
1214
0
    Py_complex cr, ci;
1215
0
    int own_r = 0;
1216
0
    int cr_is_complex = 0;
1217
0
    int ci_is_complex = 0;
1218
1219
    /* See the comment before complex_from_arg(). */
1220
0
    int nargs = (real_pos != NULL) + (imag_pos != NULL) + (r != NULL) + (i != NULL);
1221
0
    if (nargs > 2) {
1222
0
        PyErr_Format(PyExc_TypeError,
1223
0
                     "complex() takes at most 2 arguments (%d given)", nargs);
1224
0
        return NULL;
1225
0
    }
1226
0
    if (real_pos != NULL) {
1227
0
        if (r != NULL) {
1228
0
            PyErr_SetString(PyExc_TypeError, "argument for complex() given "
1229
0
                            "by name ('real') and position (1)");
1230
0
            return NULL;
1231
0
        }
1232
0
        if (imag_pos == NULL && i == NULL) {
1233
0
            return complex_from_arg(type, real_pos);
1234
0
        }
1235
0
        r = real_pos;
1236
0
    }
1237
0
    if (imag_pos != NULL) {
1238
0
        i = imag_pos;
1239
0
    }
1240
0
    if (r == NULL) {
1241
0
        if (i == NULL) {
1242
0
            return complex_subtype_from_doubles(type, 0, 0);
1243
0
        }
1244
0
        r = _PyLong_GetZero();
1245
0
    }
1246
0
    PyObject *orig_r = r;
1247
1248
    /* DEPRECATED: The call of try_complex_special_method() for the "real"
1249
     * part will be dropped after the end of the deprecation period. */
1250
0
    tmp = try_complex_special_method(r);
1251
0
    if (tmp) {
1252
0
        r = tmp;
1253
0
        own_r = 1;
1254
0
    }
1255
0
    else if (PyErr_Occurred()) {
1256
0
        return NULL;
1257
0
    }
1258
1259
0
    nbr = Py_TYPE(r)->tp_as_number;
1260
0
    if (nbr == NULL ||
1261
0
        (nbr->nb_float == NULL && nbr->nb_index == NULL && !PyComplex_Check(r)))
1262
0
    {
1263
0
        PyErr_Format(PyExc_TypeError,
1264
0
                     "complex() argument 'real' must be a real number, not %T",
1265
0
                     r);
1266
0
        if (own_r) {
1267
0
            Py_DECREF(r);
1268
0
        }
1269
0
        return NULL;
1270
0
    }
1271
0
    if (i != NULL) {
1272
0
        nbi = Py_TYPE(i)->tp_as_number;
1273
0
        if (nbi == NULL ||
1274
0
            (nbi->nb_float == NULL && nbi->nb_index == NULL && !PyComplex_Check(i)))
1275
0
        {
1276
0
            PyErr_Format(PyExc_TypeError,
1277
0
                         "complex() argument 'imag' must be a real number, not %T",
1278
0
                         i);
1279
0
            if (own_r) {
1280
0
                Py_DECREF(r);
1281
0
            }
1282
0
            return NULL;
1283
0
        }
1284
0
    }
1285
1286
    /* If we get this far, then the "real" and "imag" parts should
1287
       both be treated as numbers, and the constructor should return a
1288
       complex number equal to (real + imag*1j).
1289
1290
       The following is DEPRECATED:
1291
       Note that we do NOT assume the input to already be in canonical
1292
       form; the "real" and "imag" parts might themselves be complex
1293
       numbers, which slightly complicates the code below. */
1294
0
    if (PyComplex_Check(r)) {
1295
        /* Note that if r is of a complex subtype, we're only
1296
           retaining its real & imag parts here, and the return
1297
           value is (properly) of the builtin complex type. */
1298
0
        cr = ((PyComplexObject*)r)->cval;
1299
0
        cr_is_complex = 1;
1300
0
        if (own_r) {
1301
            /* r was a newly created complex number, rather
1302
               than the original "real" argument. */
1303
0
            Py_DECREF(r);
1304
0
        }
1305
0
        nbr = Py_TYPE(orig_r)->tp_as_number;
1306
0
        if (nbr == NULL ||
1307
0
            (nbr->nb_float == NULL && nbr->nb_index == NULL))
1308
0
        {
1309
0
            if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1310
0
                    "complex() argument 'real' must be a real number, not %T",
1311
0
                    orig_r)) {
1312
0
                return NULL;
1313
0
            }
1314
0
        }
1315
0
    }
1316
0
    else {
1317
        /* The "real" part really is entirely real, and contributes
1318
           nothing in the imaginary direction.
1319
           Just treat it as a double. */
1320
0
        tmp = PyNumber_Float(r);
1321
0
        assert(!own_r);
1322
0
        if (tmp == NULL)
1323
0
            return NULL;
1324
0
        assert(PyFloat_Check(tmp));
1325
0
        cr.real = PyFloat_AsDouble(tmp);
1326
0
        cr.imag = 0.0;
1327
0
        Py_DECREF(tmp);
1328
0
    }
1329
0
    if (i == NULL) {
1330
0
        ci.real = cr.imag;
1331
0
    }
1332
0
    else if (PyComplex_Check(i)) {
1333
0
        if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1334
0
                "complex() argument 'imag' must be a real number, not %T",
1335
0
                i)) {
1336
0
            return NULL;
1337
0
        }
1338
0
        ci = ((PyComplexObject*)i)->cval;
1339
0
        ci_is_complex = 1;
1340
0
    } else {
1341
        /* The "imag" part really is entirely imaginary, and
1342
           contributes nothing in the real direction.
1343
           Just treat it as a double. */
1344
0
        tmp = PyNumber_Float(i);
1345
0
        if (tmp == NULL)
1346
0
            return NULL;
1347
0
        ci.real = PyFloat_AsDouble(tmp);
1348
0
        Py_DECREF(tmp);
1349
0
    }
1350
    /*  If the input was in canonical form, then the "real" and "imag"
1351
        parts are real numbers, so that ci.imag and cr.imag are zero.
1352
        We need this correction in case they were not real numbers. */
1353
1354
0
    if (ci_is_complex) {
1355
0
        cr.real -= ci.imag;
1356
0
    }
1357
0
    if (cr_is_complex && i != NULL) {
1358
0
        ci.real += cr.imag;
1359
0
    }
1360
0
    return complex_subtype_from_doubles(type, cr.real, ci.real);
1361
0
}
1362
1363
/*[clinic input]
1364
@classmethod
1365
complex.from_number
1366
1367
    number: object
1368
    /
1369
1370
Convert number to a complex floating-point number.
1371
[clinic start generated code]*/
1372
1373
static PyObject *
1374
complex_from_number_impl(PyTypeObject *type, PyObject *number)
1375
/*[clinic end generated code: output=7248bb593e1871e1 input=3f8bdd3a2bc3facd]*/
1376
0
{
1377
0
    if (PyComplex_CheckExact(number) && type == &PyComplex_Type) {
1378
0
        Py_INCREF(number);
1379
0
        return number;
1380
0
    }
1381
0
    Py_complex cv = PyComplex_AsCComplex(number);
1382
0
    if (cv.real == -1.0 && PyErr_Occurred()) {
1383
0
        return NULL;
1384
0
    }
1385
0
    PyObject *result = PyComplex_FromCComplex(cv);
1386
0
    if (type != &PyComplex_Type && result != NULL) {
1387
0
        Py_SETREF(result, PyObject_CallOneArg((PyObject *)type, result));
1388
0
    }
1389
0
    return result;
1390
0
}
1391
1392
static PyMethodDef complex_methods[] = {
1393
    COMPLEX_FROM_NUMBER_METHODDEF
1394
    COMPLEX_CONJUGATE_METHODDEF
1395
    COMPLEX___COMPLEX___METHODDEF
1396
    COMPLEX___GETNEWARGS___METHODDEF
1397
    COMPLEX___FORMAT___METHODDEF
1398
    {NULL,              NULL}           /* sentinel */
1399
};
1400
1401
static PyMemberDef complex_members[] = {
1402
    {"real", Py_T_DOUBLE, offsetof(PyComplexObject, cval.real), Py_READONLY,
1403
     "the real part of a complex number"},
1404
    {"imag", Py_T_DOUBLE, offsetof(PyComplexObject, cval.imag), Py_READONLY,
1405
     "the imaginary part of a complex number"},
1406
    {0},
1407
};
1408
1409
static PyNumberMethods complex_as_number = {
1410
    complex_add,                                /* nb_add */
1411
    complex_sub,                                /* nb_subtract */
1412
    complex_mul,                                /* nb_multiply */
1413
    0,                                          /* nb_remainder */
1414
    0,                                          /* nb_divmod */
1415
    complex_pow,                                /* nb_power */
1416
    complex_neg,                                /* nb_negative */
1417
    complex_pos,                                /* nb_positive */
1418
    complex_abs,                                /* nb_absolute */
1419
    complex_bool,                               /* nb_bool */
1420
    0,                                          /* nb_invert */
1421
    0,                                          /* nb_lshift */
1422
    0,                                          /* nb_rshift */
1423
    0,                                          /* nb_and */
1424
    0,                                          /* nb_xor */
1425
    0,                                          /* nb_or */
1426
    0,                                          /* nb_int */
1427
    0,                                          /* nb_reserved */
1428
    0,                                          /* nb_float */
1429
    0,                                          /* nb_inplace_add */
1430
    0,                                          /* nb_inplace_subtract */
1431
    0,                                          /* nb_inplace_multiply*/
1432
    0,                                          /* nb_inplace_remainder */
1433
    0,                                          /* nb_inplace_power */
1434
    0,                                          /* nb_inplace_lshift */
1435
    0,                                          /* nb_inplace_rshift */
1436
    0,                                          /* nb_inplace_and */
1437
    0,                                          /* nb_inplace_xor */
1438
    0,                                          /* nb_inplace_or */
1439
    0,                                          /* nb_floor_divide */
1440
    complex_div,                                /* nb_true_divide */
1441
    0,                                          /* nb_inplace_floor_divide */
1442
    0,                                          /* nb_inplace_true_divide */
1443
};
1444
1445
PyTypeObject PyComplex_Type = {
1446
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
1447
    "complex",
1448
    sizeof(PyComplexObject),
1449
    0,
1450
    complex_dealloc,                            /* tp_dealloc */
1451
    0,                                          /* tp_vectorcall_offset */
1452
    0,                                          /* tp_getattr */
1453
    0,                                          /* tp_setattr */
1454
    0,                                          /* tp_as_async */
1455
    complex_repr,                               /* tp_repr */
1456
    &complex_as_number,                         /* tp_as_number */
1457
    0,                                          /* tp_as_sequence */
1458
    0,                                          /* tp_as_mapping */
1459
    complex_hash,                               /* tp_hash */
1460
    0,                                          /* tp_call */
1461
    0,                                          /* tp_str */
1462
    PyObject_GenericGetAttr,                    /* tp_getattro */
1463
    0,                                          /* tp_setattro */
1464
    0,                                          /* tp_as_buffer */
1465
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,   /* tp_flags */
1466
    complex_new__doc__,                         /* tp_doc */
1467
    0,                                          /* tp_traverse */
1468
    0,                                          /* tp_clear */
1469
    complex_richcompare,                        /* tp_richcompare */
1470
    0,                                          /* tp_weaklistoffset */
1471
    0,                                          /* tp_iter */
1472
    0,                                          /* tp_iternext */
1473
    complex_methods,                            /* tp_methods */
1474
    complex_members,                            /* tp_members */
1475
    0,                                          /* tp_getset */
1476
    0,                                          /* tp_base */
1477
    0,                                          /* tp_dict */
1478
    0,                                          /* tp_descr_get */
1479
    0,                                          /* tp_descr_set */
1480
    0,                                          /* tp_dictoffset */
1481
    0,                                          /* tp_init */
1482
    PyType_GenericAlloc,                        /* tp_alloc */
1483
    complex_new,                                /* tp_new */
1484
    PyObject_Free,                              /* tp_free */
1485
    .tp_vectorcall = complex_vectorcall,
1486
    .tp_version_tag = _Py_TYPE_VERSION_COMPLEX,
1487
};