Coverage Report

Created: 2025-08-26 06:26

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