blob: c87b9e8de2a6787ecd99bf28d5892105d758d14c [file] [log] [blame]
Guido van Rossum96783941997-05-20 18:21:34 +00001
Guido van Rossumf9fca921996-01-12 00:47:05 +00002/* Complex object implementation */
3
4/* Borrows heavily from floatobject.c */
5
Guido van Rossum96783941997-05-20 18:21:34 +00006/* Submitted by Jim Hugunin */
7
Guido van Rossumc0b618a1997-05-02 03:12:38 +00008#include "Python.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00009#include "structmember.h"
Guido van Rossumf9fca921996-01-12 00:47:05 +000010
Guido van Rossum65ce6de2002-06-13 17:07:07 +000011#ifndef WITHOUT_COMPLEX
12
Tim Peters70695122001-03-11 08:37:29 +000013/* Precisions used by repr() and str(), respectively.
14
15 The repr() precision (17 significant decimal digits) is the minimal number
16 that is guaranteed to have enough precision so that if the number is read
17 back in the exact same binary value is recreated. This is true for IEEE
18 floating point by design, and also happens to work for all other modern
19 hardware.
20
21 The str() precision is chosen so that in most cases, the rounding noise
22 created by various operations is suppressed, while giving plenty of
23 precision for practical use.
24*/
25
26#define PREC_REPR 17
27#define PREC_STR 12
Guido van Rossumf9fca921996-01-12 00:47:05 +000028
29/* elementary operations on complex numbers */
30
Guido van Rossum9e720e31996-07-21 02:31:35 +000031static Py_complex c_1 = {1., 0.};
Guido van Rossumf9fca921996-01-12 00:47:05 +000032
Tim Peters0f336042001-03-18 08:21:57 +000033Py_complex
34c_sum(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +000035{
Guido van Rossum9e720e31996-07-21 02:31:35 +000036 Py_complex r;
Guido van Rossumf9fca921996-01-12 00:47:05 +000037 r.real = a.real + b.real;
38 r.imag = a.imag + b.imag;
39 return r;
40}
41
Tim Peters0f336042001-03-18 08:21:57 +000042Py_complex
43c_diff(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +000044{
Guido van Rossum9e720e31996-07-21 02:31:35 +000045 Py_complex r;
Guido van Rossumf9fca921996-01-12 00:47:05 +000046 r.real = a.real - b.real;
47 r.imag = a.imag - b.imag;
48 return r;
49}
50
Tim Peters0f336042001-03-18 08:21:57 +000051Py_complex
52c_neg(Py_complex a)
Guido van Rossumf9fca921996-01-12 00:47:05 +000053{
Guido van Rossum9e720e31996-07-21 02:31:35 +000054 Py_complex r;
Guido van Rossumf9fca921996-01-12 00:47:05 +000055 r.real = -a.real;
56 r.imag = -a.imag;
57 return r;
58}
59
Tim Peters0f336042001-03-18 08:21:57 +000060Py_complex
61c_prod(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +000062{
Guido van Rossum9e720e31996-07-21 02:31:35 +000063 Py_complex r;
Guido van Rossumf9fca921996-01-12 00:47:05 +000064 r.real = a.real*b.real - a.imag*b.imag;
65 r.imag = a.real*b.imag + a.imag*b.real;
66 return r;
67}
68
Tim Peters0f336042001-03-18 08:21:57 +000069Py_complex
70c_quot(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +000071{
Tim Peters0f336042001-03-18 08:21:57 +000072 /******************************************************************
73 This was the original algorithm. It's grossly prone to spurious
74 overflow and underflow errors. It also merrily divides by 0 despite
75 checking for that(!). The code still serves a doc purpose here, as
76 the algorithm following is a simple by-cases transformation of this
77 one:
78
Guido van Rossum9e720e31996-07-21 02:31:35 +000079 Py_complex r;
Guido van Rossumf9fca921996-01-12 00:47:05 +000080 double d = b.real*b.real + b.imag*b.imag;
81 if (d == 0.)
Guido van Rossum96783941997-05-20 18:21:34 +000082 errno = EDOM;
Guido van Rossumf9fca921996-01-12 00:47:05 +000083 r.real = (a.real*b.real + a.imag*b.imag)/d;
84 r.imag = (a.imag*b.real - a.real*b.imag)/d;
85 return r;
Tim Peters0f336042001-03-18 08:21:57 +000086 ******************************************************************/
87
88 /* This algorithm is better, and is pretty obvious: first divide the
89 * numerators and denominator by whichever of {b.real, b.imag} has
90 * larger magnitude. The earliest reference I found was to CACM
91 * Algorithm 116 (Complex Division, Robert L. Smith, Stanford
92 * University). As usual, though, we're still ignoring all IEEE
93 * endcases.
94 */
95 Py_complex r; /* the result */
96 const double abs_breal = b.real < 0 ? -b.real : b.real;
97 const double abs_bimag = b.imag < 0 ? -b.imag : b.imag;
98
99 if (abs_breal >= abs_bimag) {
100 /* divide tops and bottom by b.real */
101 if (abs_breal == 0.0) {
102 errno = EDOM;
103 r.real = r.imag = 0.0;
104 }
105 else {
106 const double ratio = b.imag / b.real;
107 const double denom = b.real + b.imag * ratio;
108 r.real = (a.real + a.imag * ratio) / denom;
109 r.imag = (a.imag - a.real * ratio) / denom;
110 }
111 }
112 else {
113 /* divide tops and bottom by b.imag */
114 const double ratio = b.real / b.imag;
115 const double denom = b.real * ratio + b.imag;
116 assert(b.imag != 0.0);
117 r.real = (a.real * ratio + a.imag) / denom;
118 r.imag = (a.imag * ratio - a.real) / denom;
119 }
120 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000121}
122
Tim Peters0f336042001-03-18 08:21:57 +0000123Py_complex
124c_pow(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000125{
Guido van Rossum9e720e31996-07-21 02:31:35 +0000126 Py_complex r;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000127 double vabs,len,at,phase;
128 if (b.real == 0. && b.imag == 0.) {
129 r.real = 1.;
130 r.imag = 0.;
131 }
132 else if (a.real == 0. && a.imag == 0.) {
133 if (b.imag != 0. || b.real < 0.)
Tim Petersbab22be2002-03-22 02:48:46 +0000134 errno = EDOM;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000135 r.real = 0.;
136 r.imag = 0.;
137 }
138 else {
139 vabs = hypot(a.real,a.imag);
140 len = pow(vabs,b.real);
Martin v. Löwis387c5472001-09-06 08:16:17 +0000141 at = atan2(a.imag, a.real);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000142 phase = at*b.real;
143 if (b.imag != 0.0) {
144 len /= exp(at*b.imag);
145 phase += b.imag*log(vabs);
146 }
147 r.real = len*cos(phase);
148 r.imag = len*sin(phase);
149 }
150 return r;
151}
152
Tim Peters0f336042001-03-18 08:21:57 +0000153static Py_complex
154c_powu(Py_complex x, long n)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000155{
Guido van Rossum926518b1996-08-19 19:30:45 +0000156 Py_complex r, p;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000157 long mask = 1;
Guido van Rossum926518b1996-08-19 19:30:45 +0000158 r = c_1;
159 p = x;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000160 while (mask > 0 && n >= mask) {
161 if (n & mask)
162 r = c_prod(r,p);
163 mask <<= 1;
164 p = c_prod(p,p);
165 }
166 return r;
167}
168
Tim Peters0f336042001-03-18 08:21:57 +0000169static Py_complex
170c_powi(Py_complex x, long n)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000171{
Guido van Rossum9e720e31996-07-21 02:31:35 +0000172 Py_complex cn;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000173
174 if (n > 100 || n < -100) {
175 cn.real = (double) n;
176 cn.imag = 0.;
177 return c_pow(x,cn);
178 }
179 else if (n > 0)
180 return c_powu(x,n);
181 else
182 return c_quot(c_1,c_powu(x,-n));
183
184}
185
Tim Peters6d6c1a32001-08-02 04:15:00 +0000186static PyObject *
187complex_subtype_from_c_complex(PyTypeObject *type, Py_complex cval)
188{
189 PyObject *op;
190
Georg Brandl6b50c632006-06-01 08:27:32 +0000191 op = type->tp_alloc(type, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000192 if (op != NULL)
193 ((PyComplexObject *)op)->cval = cval;
194 return op;
195}
196
Guido van Rossumf9fca921996-01-12 00:47:05 +0000197PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000198PyComplex_FromCComplex(Py_complex cval)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000199{
Guido van Rossumb18618d2000-05-03 23:44:39 +0000200 register PyComplexObject *op;
201
Guido van Rossume3a8e7e2002-08-19 19:26:42 +0000202 /* Inline PyObject_New */
Guido van Rossumb18618d2000-05-03 23:44:39 +0000203 op = (PyComplexObject *) PyObject_MALLOC(sizeof(PyComplexObject));
Guido van Rossumf9fca921996-01-12 00:47:05 +0000204 if (op == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000205 return PyErr_NoMemory();
Guido van Rossumb18618d2000-05-03 23:44:39 +0000206 PyObject_INIT(op, &PyComplex_Type);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000207 op->cval = cval;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000208 return (PyObject *) op;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000209}
210
Tim Peters6d6c1a32001-08-02 04:15:00 +0000211static PyObject *
212complex_subtype_from_doubles(PyTypeObject *type, double real, double imag)
213{
214 Py_complex c;
215 c.real = real;
216 c.imag = imag;
217 return complex_subtype_from_c_complex(type, c);
218}
219
Guido van Rossumf9fca921996-01-12 00:47:05 +0000220PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000221PyComplex_FromDoubles(double real, double imag)
Guido van Rossum926518b1996-08-19 19:30:45 +0000222{
223 Py_complex c;
224 c.real = real;
225 c.imag = imag;
226 return PyComplex_FromCComplex(c);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000227}
228
229double
Fred Drake4288c802000-07-09 04:36:04 +0000230PyComplex_RealAsDouble(PyObject *op)
Guido van Rossum926518b1996-08-19 19:30:45 +0000231{
232 if (PyComplex_Check(op)) {
233 return ((PyComplexObject *)op)->cval.real;
Fred Drake4288c802000-07-09 04:36:04 +0000234 }
235 else {
Guido van Rossum926518b1996-08-19 19:30:45 +0000236 return PyFloat_AsDouble(op);
237 }
Guido van Rossumf9fca921996-01-12 00:47:05 +0000238}
239
240double
Fred Drake4288c802000-07-09 04:36:04 +0000241PyComplex_ImagAsDouble(PyObject *op)
Guido van Rossum926518b1996-08-19 19:30:45 +0000242{
243 if (PyComplex_Check(op)) {
244 return ((PyComplexObject *)op)->cval.imag;
Fred Drake4288c802000-07-09 04:36:04 +0000245 }
246 else {
Guido van Rossum926518b1996-08-19 19:30:45 +0000247 return 0.0;
248 }
Guido van Rossumf9fca921996-01-12 00:47:05 +0000249}
250
Guido van Rossum9e720e31996-07-21 02:31:35 +0000251Py_complex
Fred Drake4288c802000-07-09 04:36:04 +0000252PyComplex_AsCComplex(PyObject *op)
Guido van Rossum926518b1996-08-19 19:30:45 +0000253{
Guido van Rossum9e720e31996-07-21 02:31:35 +0000254 Py_complex cv;
Georg Brandl2b869942007-03-17 16:08:45 +0000255 PyObject *newop = NULL;
256 static PyObject *complex_str = NULL;
257
258 assert(op);
259 /* If op is already of type PyComplex_Type, return its value */
Guido van Rossumcf3d1081996-01-12 01:21:14 +0000260 if (PyComplex_Check(op)) {
261 return ((PyComplexObject *)op)->cval;
Fred Drake4288c802000-07-09 04:36:04 +0000262 }
Georg Brandl2b869942007-03-17 16:08:45 +0000263 /* If not, use op's __complex__ method, if it exists */
Christian Heimesd7e1b2b2008-01-28 02:07:53 +0000264
Georg Brandl2b869942007-03-17 16:08:45 +0000265 /* return -1 on failure */
266 cv.real = -1.;
267 cv.imag = 0.;
Christian Heimesd7e1b2b2008-01-28 02:07:53 +0000268
269 if (complex_str == NULL) {
270 if (!(complex_str = PyString_InternFromString("__complex__")))
271 return cv;
272 }
Georg Brandl2b869942007-03-17 16:08:45 +0000273
274 if (PyInstance_Check(op)) {
275 /* this can go away in python 3000 */
Christian Heimesd7e1b2b2008-01-28 02:07:53 +0000276 if (PyObject_HasAttr(op, complex_str)) {
Georg Brandl2b869942007-03-17 16:08:45 +0000277 newop = PyObject_CallMethod(op, "__complex__", NULL);
278 if (!newop)
279 return cv;
280 }
281 /* else try __float__ */
282 } else {
283 PyObject *complexfunc;
Georg Brandl2b869942007-03-17 16:08:45 +0000284 complexfunc = _PyType_Lookup(op->ob_type, complex_str);
285 /* complexfunc is a borrowed reference */
286 if (complexfunc) {
287 newop = PyObject_CallFunctionObjArgs(complexfunc, op, NULL);
288 if (!newop)
289 return cv;
290 }
291 }
292
293 if (newop) {
294 if (!PyComplex_Check(newop)) {
295 PyErr_SetString(PyExc_TypeError,
296 "__complex__ should return a complex object");
297 Py_DECREF(newop);
298 return cv;
299 }
300 cv = ((PyComplexObject *)newop)->cval;
301 Py_DECREF(newop);
302 return cv;
303 }
304 /* If neither of the above works, interpret op as a float giving the
305 real part of the result, and fill in the imaginary part as 0. */
Fred Drake4288c802000-07-09 04:36:04 +0000306 else {
Georg Brandl2b869942007-03-17 16:08:45 +0000307 /* PyFloat_AsDouble will return -1 on failure */
Guido van Rossumcf3d1081996-01-12 01:21:14 +0000308 cv.real = PyFloat_AsDouble(op);
Guido van Rossumcf3d1081996-01-12 01:21:14 +0000309 return cv;
Tim Peters70695122001-03-11 08:37:29 +0000310 }
Guido van Rossumcf3d1081996-01-12 01:21:14 +0000311}
312
Guido van Rossumf9fca921996-01-12 00:47:05 +0000313static void
Fred Drake4288c802000-07-09 04:36:04 +0000314complex_dealloc(PyObject *op)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000315{
Guido van Rossum9475a232001-10-05 20:51:39 +0000316 op->ob_type->tp_free(op);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000317}
318
319
Guido van Rossum363078a1996-05-24 20:45:01 +0000320static void
Barry Warsaw01d697a2001-11-28 20:50:56 +0000321complex_to_buf(char *buf, int bufsz, PyComplexObject *v, int precision)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000322{
Martin v. Löwis737ea822004-06-08 18:52:54 +0000323 char format[32];
324 if (v->cval.real == 0.) {
Christian Heimes2f0da532008-02-15 06:57:08 +0000325 if (!Py_IS_FINITE(v->cval.imag)) {
326 if (Py_IS_NAN(v->cval.imag))
327 strncpy(buf, "nan*j", 6);
328 /* else if (copysign(1, v->cval.imag) == 1) */
329 else if (v->cval.imag > 0)
330 strncpy(buf, "inf*j", 6);
331 else
332 strncpy(buf, "-inf*j", 7);
333 }
334 else {
335 PyOS_snprintf(format, sizeof(format), "%%.%ig", precision);
336 PyOS_ascii_formatd(buf, bufsz - 1, format, v->cval.imag);
337 strncat(buf, "j", 1);
338 }
Martin v. Löwis737ea822004-06-08 18:52:54 +0000339 } else {
340 char re[64], im[64];
Georg Brandlc404ff22005-09-16 06:42:26 +0000341 /* Format imaginary part with sign, real part without */
Christian Heimes2f0da532008-02-15 06:57:08 +0000342 if (!Py_IS_FINITE(v->cval.real)) {
343 if (Py_IS_NAN(v->cval.real))
344 strncpy(re, "nan", 4);
345 /* else if (copysign(1, v->cval.real) == 1) */
346 else if (v->cval.real > 0)
347 strncpy(re, "inf", 4);
348 else
349 strncpy(re, "-inf", 5);
350 }
351 else {
352 PyOS_snprintf(format, sizeof(format), "%%.%ig", precision);
353 PyOS_ascii_formatd(re, sizeof(re), format, v->cval.real);
354 }
355 if (!Py_IS_FINITE(v->cval.imag)) {
356 if (Py_IS_NAN(v->cval.imag))
357 strncpy(im, "+nan*", 6);
358 /* else if (copysign(1, v->cval.imag) == 1) */
359 else if (v->cval.imag > 0)
360 strncpy(im, "+inf*", 6);
361 else
362 strncpy(im, "-inf*", 6);
363 }
364 else {
365 PyOS_snprintf(format, sizeof(format), "%%+.%ig", precision);
366 PyOS_ascii_formatd(im, sizeof(im), format, v->cval.imag);
367 }
Georg Brandlc404ff22005-09-16 06:42:26 +0000368 PyOS_snprintf(buf, bufsz, "(%s%sj)", re, im);
Martin v. Löwis737ea822004-06-08 18:52:54 +0000369 }
Guido van Rossumf9fca921996-01-12 00:47:05 +0000370}
371
372static int
Fred Drake4288c802000-07-09 04:36:04 +0000373complex_print(PyComplexObject *v, FILE *fp, int flags)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000374{
375 char buf[100];
Barry Warsaw01d697a2001-11-28 20:50:56 +0000376 complex_to_buf(buf, sizeof(buf), v,
Tim Peters70695122001-03-11 08:37:29 +0000377 (flags & Py_PRINT_RAW) ? PREC_STR : PREC_REPR);
Brett Cannon01531592007-09-17 03:28:34 +0000378 Py_BEGIN_ALLOW_THREADS
Guido van Rossumf9fca921996-01-12 00:47:05 +0000379 fputs(buf, fp);
Brett Cannon01531592007-09-17 03:28:34 +0000380 Py_END_ALLOW_THREADS
Guido van Rossumf9fca921996-01-12 00:47:05 +0000381 return 0;
382}
383
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000384static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000385complex_repr(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000386{
387 char buf[100];
Barry Warsaw01d697a2001-11-28 20:50:56 +0000388 complex_to_buf(buf, sizeof(buf), v, PREC_REPR);
Tim Peters70695122001-03-11 08:37:29 +0000389 return PyString_FromString(buf);
390}
391
392static PyObject *
393complex_str(PyComplexObject *v)
394{
395 char buf[100];
Barry Warsaw01d697a2001-11-28 20:50:56 +0000396 complex_to_buf(buf, sizeof(buf), v, PREC_STR);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000397 return PyString_FromString(buf);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000398}
399
Guido van Rossumf9fca921996-01-12 00:47:05 +0000400static long
Fred Drake4288c802000-07-09 04:36:04 +0000401complex_hash(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000402{
Tim Peters39dce292000-08-15 03:34:48 +0000403 long hashreal, hashimag, combined;
404 hashreal = _Py_HashDouble(v->cval.real);
405 if (hashreal == -1)
406 return -1;
407 hashimag = _Py_HashDouble(v->cval.imag);
408 if (hashimag == -1)
409 return -1;
410 /* Note: if the imaginary part is 0, hashimag is 0 now,
411 * so the following returns hashreal unchanged. This is
412 * important because numbers of different types that
413 * compare equal must have the same hash value, so that
414 * hash(x + 0*j) must equal hash(x).
415 */
416 combined = hashreal + 1000003 * hashimag;
417 if (combined == -1)
418 combined = -2;
419 return combined;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000420}
421
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000422/* This macro may return! */
423#define TO_COMPLEX(obj, c) \
424 if (PyComplex_Check(obj)) \
425 c = ((PyComplexObject *)(obj))->cval; \
426 else if (to_complex(&(obj), &(c)) < 0) \
427 return (obj)
428
429static int
430to_complex(PyObject **pobj, Py_complex *pc)
431{
432 PyObject *obj = *pobj;
433
434 pc->real = pc->imag = 0.0;
435 if (PyInt_Check(obj)) {
436 pc->real = PyInt_AS_LONG(obj);
437 return 0;
438 }
439 if (PyLong_Check(obj)) {
440 pc->real = PyLong_AsDouble(obj);
441 if (pc->real == -1.0 && PyErr_Occurred()) {
442 *pobj = NULL;
443 return -1;
444 }
445 return 0;
446 }
447 if (PyFloat_Check(obj)) {
448 pc->real = PyFloat_AsDouble(obj);
449 return 0;
450 }
451 Py_INCREF(Py_NotImplemented);
452 *pobj = Py_NotImplemented;
453 return -1;
454}
455
456
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000457static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000458complex_add(PyComplexObject *v, PyComplexObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000459{
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000460 Py_complex result;
461 PyFPE_START_PROTECT("complex_add", return 0)
462 result = c_sum(v->cval,w->cval);
Guido van Rossum45b83911997-03-14 04:32:50 +0000463 PyFPE_END_PROTECT(result)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000464 return PyComplex_FromCComplex(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000465}
466
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000467static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000468complex_sub(PyComplexObject *v, PyComplexObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000469{
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000470 Py_complex result;
471 PyFPE_START_PROTECT("complex_sub", return 0)
472 result = c_diff(v->cval,w->cval);
Guido van Rossum45b83911997-03-14 04:32:50 +0000473 PyFPE_END_PROTECT(result)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000474 return PyComplex_FromCComplex(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000475}
476
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000477static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000478complex_mul(PyComplexObject *v, PyComplexObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000479{
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000480 Py_complex result;
481 PyFPE_START_PROTECT("complex_mul", return 0)
482 result = c_prod(v->cval,w->cval);
Guido van Rossum45b83911997-03-14 04:32:50 +0000483 PyFPE_END_PROTECT(result)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000484 return PyComplex_FromCComplex(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000485}
486
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000487static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000488complex_div(PyComplexObject *v, PyComplexObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000489{
Guido van Rossum9e720e31996-07-21 02:31:35 +0000490 Py_complex quot;
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000491 PyFPE_START_PROTECT("complex_div", return 0)
Guido van Rossum96783941997-05-20 18:21:34 +0000492 errno = 0;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000493 quot = c_quot(v->cval,w->cval);
Guido van Rossum45b83911997-03-14 04:32:50 +0000494 PyFPE_END_PROTECT(quot)
Guido van Rossum96783941997-05-20 18:21:34 +0000495 if (errno == EDOM) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000496 PyErr_SetString(PyExc_ZeroDivisionError, "complex division");
Guido van Rossumf9fca921996-01-12 00:47:05 +0000497 return NULL;
498 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000499 return PyComplex_FromCComplex(quot);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000500}
501
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000502static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +0000503complex_classic_div(PyComplexObject *v, PyComplexObject *w)
504{
505 Py_complex quot;
506
Guido van Rossum1832de42001-09-04 03:51:09 +0000507 if (Py_DivisionWarningFlag >= 2 &&
Guido van Rossum393661d2001-08-31 17:40:15 +0000508 PyErr_Warn(PyExc_DeprecationWarning,
509 "classic complex division") < 0)
510 return NULL;
511
512 PyFPE_START_PROTECT("complex_classic_div", return 0)
513 errno = 0;
514 quot = c_quot(v->cval,w->cval);
515 PyFPE_END_PROTECT(quot)
516 if (errno == EDOM) {
517 PyErr_SetString(PyExc_ZeroDivisionError, "complex division");
518 return NULL;
519 }
520 return PyComplex_FromCComplex(quot);
521}
522
523static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000524complex_remainder(PyComplexObject *v, PyComplexObject *w)
Guido van Rossumee09fc11996-09-11 13:55:55 +0000525{
Georg Brandl96f21842008-01-19 10:18:07 +0000526 Py_complex div, mod;
Guido van Rossum69cf3c72002-04-15 12:39:12 +0000527
528 if (PyErr_Warn(PyExc_DeprecationWarning,
529 "complex divmod(), // and % are deprecated") < 0)
530 return NULL;
531
Guido van Rossum96783941997-05-20 18:21:34 +0000532 errno = 0;
Guido van Rossum3be12e91996-09-12 20:56:18 +0000533 div = c_quot(v->cval,w->cval); /* The raw divisor value. */
Guido van Rossum96783941997-05-20 18:21:34 +0000534 if (errno == EDOM) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000535 PyErr_SetString(PyExc_ZeroDivisionError, "complex remainder");
Guido van Rossum3be12e91996-09-12 20:56:18 +0000536 return NULL;
537 }
538 div.real = floor(div.real); /* Use the floor of the real part. */
539 div.imag = 0.0;
540 mod = c_diff(v->cval, c_prod(w->cval, div));
541
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000542 return PyComplex_FromCComplex(mod);
Guido van Rossumee09fc11996-09-11 13:55:55 +0000543}
544
Guido van Rossumee09fc11996-09-11 13:55:55 +0000545
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000546static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000547complex_divmod(PyComplexObject *v, PyComplexObject *w)
Guido van Rossum3be12e91996-09-12 20:56:18 +0000548{
Georg Brandl96f21842008-01-19 10:18:07 +0000549 Py_complex div, mod;
Guido van Rossum3be12e91996-09-12 20:56:18 +0000550 PyObject *d, *m, *z;
Guido van Rossum9ec4c782002-04-15 01:41:56 +0000551
552 if (PyErr_Warn(PyExc_DeprecationWarning,
Guido van Rossum69cf3c72002-04-15 12:39:12 +0000553 "complex divmod(), // and % are deprecated") < 0)
Guido van Rossum9ec4c782002-04-15 01:41:56 +0000554 return NULL;
555
Guido van Rossum96783941997-05-20 18:21:34 +0000556 errno = 0;
Guido van Rossum3be12e91996-09-12 20:56:18 +0000557 div = c_quot(v->cval,w->cval); /* The raw divisor value. */
Guido van Rossum96783941997-05-20 18:21:34 +0000558 if (errno == EDOM) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000559 PyErr_SetString(PyExc_ZeroDivisionError, "complex divmod()");
Guido van Rossum3be12e91996-09-12 20:56:18 +0000560 return NULL;
561 }
562 div.real = floor(div.real); /* Use the floor of the real part. */
563 div.imag = 0.0;
564 mod = c_diff(v->cval, c_prod(w->cval, div));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000565 d = PyComplex_FromCComplex(div);
566 m = PyComplex_FromCComplex(mod);
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000567 z = PyTuple_Pack(2, d, m);
Guido van Rossum3be12e91996-09-12 20:56:18 +0000568 Py_XDECREF(d);
569 Py_XDECREF(m);
570 return z;
571}
Guido van Rossumf9fca921996-01-12 00:47:05 +0000572
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000573static PyObject *
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000574complex_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000575{
Guido van Rossum9e720e31996-07-21 02:31:35 +0000576 Py_complex p;
577 Py_complex exponent;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000578 long int_exponent;
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000579 Py_complex a, b;
Georg Brandl96f21842008-01-19 10:18:07 +0000580 TO_COMPLEX(v, a);
581 TO_COMPLEX(w, b);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000582
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000583 if (z!=Py_None) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000584 PyErr_SetString(PyExc_ValueError, "complex modulo");
Guido van Rossumf9fca921996-01-12 00:47:05 +0000585 return NULL;
586 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000587 PyFPE_START_PROTECT("complex_pow", return 0)
Guido van Rossum96783941997-05-20 18:21:34 +0000588 errno = 0;
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000589 exponent = b;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000590 int_exponent = (long)exponent.real;
591 if (exponent.imag == 0. && exponent.real == int_exponent)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000592 p = c_powi(a,int_exponent);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000593 else
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000594 p = c_pow(a,exponent);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000595
Guido van Rossum45b83911997-03-14 04:32:50 +0000596 PyFPE_END_PROTECT(p)
Tim Petersbab22be2002-03-22 02:48:46 +0000597 Py_ADJUST_ERANGE2(p.real, p.imag);
598 if (errno == EDOM) {
599 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000600 "0.0 to a negative or complex power");
Guido van Rossumf9fca921996-01-12 00:47:05 +0000601 return NULL;
602 }
Tim Petersbab22be2002-03-22 02:48:46 +0000603 else if (errno == ERANGE) {
604 PyErr_SetString(PyExc_OverflowError,
Neal Norwitz0593de32007-03-09 05:59:01 +0000605 "complex exponentiation");
Tim Petersbab22be2002-03-22 02:48:46 +0000606 return NULL;
607 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000608 return PyComplex_FromCComplex(p);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000609}
610
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000611static PyObject *
Guido van Rossum4668b002001-08-08 05:00:18 +0000612complex_int_div(PyComplexObject *v, PyComplexObject *w)
613{
614 PyObject *t, *r;
615
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000616 if (PyErr_Warn(PyExc_DeprecationWarning,
617 "complex divmod(), // and % are deprecated") < 0)
618 return NULL;
619
Guido van Rossum4668b002001-08-08 05:00:18 +0000620 t = complex_divmod(v, w);
621 if (t != NULL) {
622 r = PyTuple_GET_ITEM(t, 0);
623 Py_INCREF(r);
624 Py_DECREF(t);
625 return r;
626 }
627 return NULL;
628}
629
630static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000631complex_neg(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000632{
Guido van Rossum9e720e31996-07-21 02:31:35 +0000633 Py_complex neg;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000634 neg.real = -v->cval.real;
635 neg.imag = -v->cval.imag;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000636 return PyComplex_FromCComplex(neg);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000637}
638
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000639static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000640complex_pos(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000641{
Tim Peters2400fa42001-09-12 19:12:49 +0000642 if (PyComplex_CheckExact(v)) {
643 Py_INCREF(v);
644 return (PyObject *)v;
645 }
646 else
647 return PyComplex_FromCComplex(v->cval);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000648}
649
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000650static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000651complex_abs(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000652{
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000653 double result;
654 PyFPE_START_PROTECT("complex_abs", return 0)
655 result = hypot(v->cval.real,v->cval.imag);
Guido van Rossum45b83911997-03-14 04:32:50 +0000656 PyFPE_END_PROTECT(result)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000657 return PyFloat_FromDouble(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000658}
659
660static int
Fred Drake4288c802000-07-09 04:36:04 +0000661complex_nonzero(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000662{
Guido van Rossum3bbef601999-01-25 19:42:19 +0000663 return v->cval.real != 0.0 || v->cval.imag != 0.0;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000664}
665
666static int
Fred Drake4288c802000-07-09 04:36:04 +0000667complex_coerce(PyObject **pv, PyObject **pw)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000668{
Guido van Rossum9e720e31996-07-21 02:31:35 +0000669 Py_complex cval;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000670 cval.imag = 0.;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000671 if (PyInt_Check(*pw)) {
672 cval.real = (double)PyInt_AsLong(*pw);
673 *pw = PyComplex_FromCComplex(cval);
674 Py_INCREF(*pv);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000675 return 0;
676 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000677 else if (PyLong_Check(*pw)) {
678 cval.real = PyLong_AsDouble(*pw);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000679 if (cval.real == -1.0 && PyErr_Occurred())
680 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000681 *pw = PyComplex_FromCComplex(cval);
682 Py_INCREF(*pv);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000683 return 0;
684 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000685 else if (PyFloat_Check(*pw)) {
686 cval.real = PyFloat_AsDouble(*pw);
687 *pw = PyComplex_FromCComplex(cval);
688 Py_INCREF(*pv);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000689 return 0;
690 }
Guido van Rossum63805962001-09-19 01:13:10 +0000691 else if (PyComplex_Check(*pw)) {
692 Py_INCREF(*pv);
693 Py_INCREF(*pw);
694 return 0;
695 }
Guido van Rossumf9fca921996-01-12 00:47:05 +0000696 return 1; /* Can't do it */
697}
698
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000699static PyObject *
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000700complex_richcompare(PyObject *v, PyObject *w, int op)
701{
702 int c;
703 Py_complex i, j;
704 PyObject *res;
705
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000706 c = PyNumber_CoerceEx(&v, &w);
707 if (c < 0)
708 return NULL;
709 if (c > 0) {
710 Py_INCREF(Py_NotImplemented);
711 return Py_NotImplemented;
712 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +0000713 /* Make sure both arguments are complex. */
714 if (!(PyComplex_Check(v) && PyComplex_Check(w))) {
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000715 Py_DECREF(v);
716 Py_DECREF(w);
717 Py_INCREF(Py_NotImplemented);
718 return Py_NotImplemented;
719 }
720
721 i = ((PyComplexObject *)v)->cval;
722 j = ((PyComplexObject *)w)->cval;
723 Py_DECREF(v);
724 Py_DECREF(w);
725
Guido van Rossum22056422001-09-24 17:52:04 +0000726 if (op != Py_EQ && op != Py_NE) {
727 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger5d01aa42004-12-19 20:45:20 +0000728 "no ordering relation is defined for complex numbers");
Guido van Rossum22056422001-09-24 17:52:04 +0000729 return NULL;
730 }
731
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000732 if ((i.real == j.real && i.imag == j.imag) == (op == Py_EQ))
733 res = Py_True;
734 else
735 res = Py_False;
736
737 Py_INCREF(res);
738 return res;
739}
740
741static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000742complex_int(PyObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000743{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000744 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger0970dba2003-08-30 23:57:36 +0000745 "can't convert complex to int; use int(abs(z))");
Guido van Rossumd4ab3cd1996-09-11 22:54:37 +0000746 return NULL;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000747}
748
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000749static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000750complex_long(PyObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000751{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000752 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger0970dba2003-08-30 23:57:36 +0000753 "can't convert complex to long; use long(abs(z))");
Guido van Rossumd4ab3cd1996-09-11 22:54:37 +0000754 return NULL;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000755}
756
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000757static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000758complex_float(PyObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000759{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000760 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger0970dba2003-08-30 23:57:36 +0000761 "can't convert complex to float; use abs(z)");
Guido van Rossumd4ab3cd1996-09-11 22:54:37 +0000762 return NULL;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000763}
764
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000765static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000766complex_conjugate(PyObject *self)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000767{
Guido van Rossum926518b1996-08-19 19:30:45 +0000768 Py_complex c;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000769 c = ((PyComplexObject *)self)->cval;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000770 c.imag = -c.imag;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000771 return PyComplex_FromCComplex(c);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000772}
773
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000774PyDoc_STRVAR(complex_conjugate_doc,
775"complex.conjugate() -> complex\n"
776"\n"
777"Returns the complex conjugate of its argument. (3-4j).conjugate() == 3+4j.");
778
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000779static PyObject *
780complex_getnewargs(PyComplexObject *v)
781{
Guido van Rossum4eadfa22003-03-02 13:51:47 +0000782 return Py_BuildValue("(D)", &v->cval);
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000783}
784
Guido van Rossumf9fca921996-01-12 00:47:05 +0000785static PyMethodDef complex_methods[] = {
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000786 {"conjugate", (PyCFunction)complex_conjugate, METH_NOARGS,
787 complex_conjugate_doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000788 {"__getnewargs__", (PyCFunction)complex_getnewargs, METH_NOARGS},
Guido van Rossumf9fca921996-01-12 00:47:05 +0000789 {NULL, NULL} /* sentinel */
790};
791
Guido van Rossum6f799372001-09-20 20:46:19 +0000792static PyMemberDef complex_members[] = {
Guido van Rossumfa2e4c22002-02-08 21:26:07 +0000793 {"real", T_DOUBLE, offsetof(PyComplexObject, cval.real), READONLY,
Guido van Rossum6f799372001-09-20 20:46:19 +0000794 "the real part of a complex number"},
Guido van Rossumfa2e4c22002-02-08 21:26:07 +0000795 {"imag", T_DOUBLE, offsetof(PyComplexObject, cval.imag), READONLY,
Guido van Rossum6f799372001-09-20 20:46:19 +0000796 "the imaginary part of a complex number"},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000797 {0},
798};
Guido van Rossumf9fca921996-01-12 00:47:05 +0000799
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000800static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000801complex_subtype_from_string(PyTypeObject *type, PyObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000802{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000803 const char *s, *start;
804 char *end;
805 double x=0.0, y=0.0, z;
Collin Wintere38051d2007-03-09 20:33:07 +0000806 int got_re=0, got_im=0, got_bracket=0, done=0;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000807 int digit_or_dot;
808 int sw_error=0;
809 int sign;
810 char buffer[256]; /* For errors */
Guido van Rossum70e36882001-10-25 18:07:22 +0000811#ifdef Py_USING_UNICODE
812 char s_buffer[256];
813#endif
Martin v. Löwis18e16552006-02-15 17:27:45 +0000814 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000815
816 if (PyString_Check(v)) {
817 s = PyString_AS_STRING(v);
818 len = PyString_GET_SIZE(v);
819 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000820#ifdef Py_USING_UNICODE
Tim Peters6d6c1a32001-08-02 04:15:00 +0000821 else if (PyUnicode_Check(v)) {
Skip Montanaro429433b2006-04-18 00:35:43 +0000822 if (PyUnicode_GET_SIZE(v) >= (Py_ssize_t)sizeof(s_buffer)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000823 PyErr_SetString(PyExc_ValueError,
824 "complex() literal too large to convert");
825 return NULL;
826 }
827 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
828 PyUnicode_GET_SIZE(v),
829 s_buffer,
830 NULL))
831 return NULL;
832 s = s_buffer;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000833 len = strlen(s);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000834 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000835#endif
Tim Peters6d6c1a32001-08-02 04:15:00 +0000836 else if (PyObject_AsCharBuffer(v, &s, &len)) {
837 PyErr_SetString(PyExc_TypeError,
838 "complex() arg is not a string");
839 return NULL;
840 }
841
842 /* position on first nonblank */
843 start = s;
844 while (*s && isspace(Py_CHARMASK(*s)))
845 s++;
Georg Brandl96f21842008-01-19 10:18:07 +0000846 if (s[0] == '\0') {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000847 PyErr_SetString(PyExc_ValueError,
848 "complex() arg is an empty string");
849 return NULL;
Georg Brandl96f21842008-01-19 10:18:07 +0000850 }
Collin Wintere38051d2007-03-09 20:33:07 +0000851 if (s[0] == '(') {
852 /* Skip over possible bracket from repr(). */
853 got_bracket = 1;
854 s++;
855 while (*s && isspace(Py_CHARMASK(*s)))
856 s++;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000857 }
858
859 z = -1.0;
860 sign = 1;
861 do {
862
863 switch (*s) {
864
865 case '\0':
866 if (s-start != len) {
867 PyErr_SetString(
868 PyExc_ValueError,
869 "complex() arg contains a null byte");
870 return NULL;
871 }
872 if(!done) sw_error=1;
873 break;
874
Collin Wintere38051d2007-03-09 20:33:07 +0000875 case ')':
876 if (!got_bracket || !(got_re || got_im)) {
877 sw_error=1;
878 break;
879 }
880 got_bracket=0;
881 done=1;
882 s++;
883 while (*s && isspace(Py_CHARMASK(*s)))
884 s++;
885 if (*s) sw_error=1;
886 break;
887
Tim Peters6d6c1a32001-08-02 04:15:00 +0000888 case '-':
889 sign = -1;
890 /* Fallthrough */
891 case '+':
892 if (done) sw_error=1;
893 s++;
Collin Wintere38051d2007-03-09 20:33:07 +0000894 if ( *s=='\0'||*s=='+'||*s=='-'||*s==')'||
Tim Peters6d6c1a32001-08-02 04:15:00 +0000895 isspace(Py_CHARMASK(*s)) ) sw_error=1;
896 break;
897
898 case 'J':
899 case 'j':
900 if (got_im || done) {
901 sw_error = 1;
902 break;
903 }
904 if (z<0.0) {
905 y=sign;
906 }
907 else{
908 y=sign*z;
909 }
910 got_im=1;
911 s++;
912 if (*s!='+' && *s!='-' )
913 done=1;
914 break;
915
916 default:
917 if (isspace(Py_CHARMASK(*s))) {
918 while (*s && isspace(Py_CHARMASK(*s)))
919 s++;
Collin Wintere38051d2007-03-09 20:33:07 +0000920 if (*s && *s != ')')
Tim Peters6d6c1a32001-08-02 04:15:00 +0000921 sw_error=1;
922 else
923 done = 1;
924 break;
925 }
926 digit_or_dot =
927 (*s=='.' || isdigit(Py_CHARMASK(*s)));
928 if (done||!digit_or_dot) {
929 sw_error=1;
930 break;
931 }
932 errno = 0;
933 PyFPE_START_PROTECT("strtod", return 0)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000934 z = PyOS_ascii_strtod(s, &end) ;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000935 PyFPE_END_PROTECT(z)
936 if (errno != 0) {
Barry Warsaw01d697a2001-11-28 20:50:56 +0000937 PyOS_snprintf(buffer, sizeof(buffer),
Tim Peters6d6c1a32001-08-02 04:15:00 +0000938 "float() out of range: %.150s", s);
939 PyErr_SetString(
940 PyExc_ValueError,
941 buffer);
942 return NULL;
943 }
944 s=end;
945 if (*s=='J' || *s=='j') {
946
947 break;
948 }
949 if (got_re) {
950 sw_error=1;
951 break;
952 }
953
954 /* accept a real part */
955 x=sign*z;
956 got_re=1;
957 if (got_im) done=1;
958 z = -1.0;
959 sign = 1;
960 break;
961
962 } /* end of switch */
963
Tim Peters077f2712002-04-14 22:04:03 +0000964 } while (s - start < len && !sw_error);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000965
Collin Wintere38051d2007-03-09 20:33:07 +0000966 if (sw_error || got_bracket) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000967 PyErr_SetString(PyExc_ValueError,
968 "complex() arg is a malformed string");
969 return NULL;
970 }
971
972 return complex_subtype_from_doubles(type, x, y);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000973}
974
Tim Peters6d6c1a32001-08-02 04:15:00 +0000975static PyObject *
976complex_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
977{
Raymond Hettinger478d47a2002-06-06 15:45:38 +0000978 PyObject *r, *i, *tmp, *f;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000979 PyNumberMethods *nbr, *nbi = NULL;
980 Py_complex cr, ci;
981 int own_r = 0;
Guido van Rossum715ec182007-11-27 22:38:36 +0000982 int cr_is_complex = 0;
983 int ci_is_complex = 0;
Raymond Hettinger478d47a2002-06-06 15:45:38 +0000984 static PyObject *complexstr;
Martin v. Löwis15e62742006-02-27 16:46:16 +0000985 static char *kwlist[] = {"real", "imag", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +0000986
987 r = Py_False;
988 i = NULL;
989 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:complex", kwlist,
990 &r, &i))
991 return NULL;
Raymond Hettinger604cd6a2002-08-29 14:22:51 +0000992
Georg Brandl8f032cb2007-03-13 07:57:51 +0000993 /* Special-case for a single argument when type(arg) is complex. */
Guido van Rossum4eadfa22003-03-02 13:51:47 +0000994 if (PyComplex_CheckExact(r) && i == NULL &&
995 type == &PyComplex_Type) {
Raymond Hettinger604cd6a2002-08-29 14:22:51 +0000996 /* Note that we can't know whether it's safe to return
997 a complex *subclass* instance as-is, hence the restriction
Georg Brandl8f032cb2007-03-13 07:57:51 +0000998 to exact complexes here. If either the input or the
999 output is a complex subclass, it will be handled below
1000 as a non-orthogonal vector. */
Raymond Hettinger604cd6a2002-08-29 14:22:51 +00001001 Py_INCREF(r);
1002 return r;
1003 }
Fred Drake526c7a02001-12-13 19:52:22 +00001004 if (PyString_Check(r) || PyUnicode_Check(r)) {
1005 if (i != NULL) {
1006 PyErr_SetString(PyExc_TypeError,
1007 "complex() can't take second arg"
1008 " if first is a string");
1009 return NULL;
Georg Brandl96f21842008-01-19 10:18:07 +00001010 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001011 return complex_subtype_from_string(type, r);
Fred Drake526c7a02001-12-13 19:52:22 +00001012 }
1013 if (i != NULL && (PyString_Check(i) || PyUnicode_Check(i))) {
1014 PyErr_SetString(PyExc_TypeError,
1015 "complex() second arg can't be a string");
1016 return NULL;
1017 }
Tim Peters2400fa42001-09-12 19:12:49 +00001018
Raymond Hettinger478d47a2002-06-06 15:45:38 +00001019 /* XXX Hack to support classes with __complex__ method */
1020 if (complexstr == NULL) {
1021 complexstr = PyString_InternFromString("__complex__");
1022 if (complexstr == NULL)
1023 return NULL;
1024 }
1025 f = PyObject_GetAttr(r, complexstr);
1026 if (f == NULL)
1027 PyErr_Clear();
1028 else {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001029 PyObject *args = PyTuple_New(0);
Raymond Hettinger478d47a2002-06-06 15:45:38 +00001030 if (args == NULL)
1031 return NULL;
1032 r = PyEval_CallObject(f, args);
1033 Py_DECREF(args);
1034 Py_DECREF(f);
1035 if (r == NULL)
1036 return NULL;
1037 own_r = 1;
1038 }
Tim Peters2400fa42001-09-12 19:12:49 +00001039 nbr = r->ob_type->tp_as_number;
1040 if (i != NULL)
1041 nbi = i->ob_type->tp_as_number;
1042 if (nbr == NULL || nbr->nb_float == NULL ||
1043 ((i != NULL) && (nbi == NULL || nbi->nb_float == NULL))) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001044 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger478d47a2002-06-06 15:45:38 +00001045 "complex() argument must be a string or a number");
Tim Peters465fa3d2003-08-15 01:16:37 +00001046 if (own_r) {
1047 Py_DECREF(r);
1048 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001049 return NULL;
1050 }
Georg Brandl8f032cb2007-03-13 07:57:51 +00001051
1052 /* If we get this far, then the "real" and "imag" parts should
1053 both be treated as numbers, and the constructor should return a
1054 complex number equal to (real + imag*1j).
1055
1056 Note that we do NOT assume the input to already be in canonical
1057 form; the "real" and "imag" parts might themselves be complex
1058 numbers, which slightly complicates the code below. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001059 if (PyComplex_Check(r)) {
Tim Peters2400fa42001-09-12 19:12:49 +00001060 /* Note that if r is of a complex subtype, we're only
1061 retaining its real & imag parts here, and the return
1062 value is (properly) of the builtin complex type. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001063 cr = ((PyComplexObject*)r)->cval;
Guido van Rossum715ec182007-11-27 22:38:36 +00001064 cr_is_complex = 1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001065 if (own_r) {
1066 Py_DECREF(r);
1067 }
1068 }
1069 else {
Georg Brandl8f032cb2007-03-13 07:57:51 +00001070 /* The "real" part really is entirely real, and contributes
1071 nothing in the imaginary direction.
1072 Just treat it as a double. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001073 tmp = PyNumber_Float(r);
1074 if (own_r) {
Georg Brandl8f032cb2007-03-13 07:57:51 +00001075 /* r was a newly created complex number, rather
1076 than the original "real" argument. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001077 Py_DECREF(r);
1078 }
1079 if (tmp == NULL)
1080 return NULL;
1081 if (!PyFloat_Check(tmp)) {
1082 PyErr_SetString(PyExc_TypeError,
1083 "float(r) didn't return a float");
1084 Py_DECREF(tmp);
1085 return NULL;
1086 }
1087 cr.real = PyFloat_AsDouble(tmp);
Georg Brandl96f21842008-01-19 10:18:07 +00001088 cr.imag = 0.0; /* Shut up compiler warning */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001089 Py_DECREF(tmp);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001090 }
1091 if (i == NULL) {
1092 ci.real = 0.0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001093 }
Guido van Rossum715ec182007-11-27 22:38:36 +00001094 else if (PyComplex_Check(i)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001095 ci = ((PyComplexObject*)i)->cval;
Guido van Rossum715ec182007-11-27 22:38:36 +00001096 ci_is_complex = 1;
1097 } else {
Georg Brandl8f032cb2007-03-13 07:57:51 +00001098 /* The "imag" part really is entirely imaginary, and
1099 contributes nothing in the real direction.
1100 Just treat it as a double. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001101 tmp = (*nbi->nb_float)(i);
1102 if (tmp == NULL)
1103 return NULL;
1104 ci.real = PyFloat_AsDouble(tmp);
1105 Py_DECREF(tmp);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001106 }
Georg Brandl8f032cb2007-03-13 07:57:51 +00001107 /* If the input was in canonical form, then the "real" and "imag"
Guido van Rossum715ec182007-11-27 22:38:36 +00001108 parts are real numbers, so that ci.imag and cr.imag are zero.
Georg Brandl8f032cb2007-03-13 07:57:51 +00001109 We need this correction in case they were not real numbers. */
Guido van Rossum715ec182007-11-27 22:38:36 +00001110
1111 if (ci_is_complex) {
1112 cr.real -= ci.imag;
1113 }
1114 if (cr_is_complex) {
1115 ci.real += cr.imag;
1116 }
1117 return complex_subtype_from_doubles(type, cr.real, ci.real);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001118}
1119
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001120PyDoc_STRVAR(complex_doc,
Tim Peters2400fa42001-09-12 19:12:49 +00001121"complex(real[, imag]) -> complex number\n"
1122"\n"
1123"Create a complex number from a real part and an optional imaginary part.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001124"This is equivalent to (real + imag*1j) where imag defaults to 0.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001125
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001126static PyNumberMethods complex_as_number = {
Guido van Rossumbe4cbb12001-01-18 01:12:39 +00001127 (binaryfunc)complex_add, /* nb_add */
1128 (binaryfunc)complex_sub, /* nb_subtract */
1129 (binaryfunc)complex_mul, /* nb_multiply */
Guido van Rossum393661d2001-08-31 17:40:15 +00001130 (binaryfunc)complex_classic_div, /* nb_divide */
Guido van Rossumbe4cbb12001-01-18 01:12:39 +00001131 (binaryfunc)complex_remainder, /* nb_remainder */
1132 (binaryfunc)complex_divmod, /* nb_divmod */
1133 (ternaryfunc)complex_pow, /* nb_power */
1134 (unaryfunc)complex_neg, /* nb_negative */
1135 (unaryfunc)complex_pos, /* nb_positive */
1136 (unaryfunc)complex_abs, /* nb_absolute */
1137 (inquiry)complex_nonzero, /* nb_nonzero */
1138 0, /* nb_invert */
1139 0, /* nb_lshift */
1140 0, /* nb_rshift */
1141 0, /* nb_and */
1142 0, /* nb_xor */
1143 0, /* nb_or */
Georg Brandl347b3002006-03-30 11:57:00 +00001144 complex_coerce, /* nb_coerce */
1145 complex_int, /* nb_int */
1146 complex_long, /* nb_long */
1147 complex_float, /* nb_float */
Guido van Rossumbe4cbb12001-01-18 01:12:39 +00001148 0, /* nb_oct */
1149 0, /* nb_hex */
Guido van Rossum4668b002001-08-08 05:00:18 +00001150 0, /* nb_inplace_add */
1151 0, /* nb_inplace_subtract */
1152 0, /* nb_inplace_multiply*/
1153 0, /* nb_inplace_divide */
1154 0, /* nb_inplace_remainder */
1155 0, /* nb_inplace_power */
1156 0, /* nb_inplace_lshift */
1157 0, /* nb_inplace_rshift */
1158 0, /* nb_inplace_and */
1159 0, /* nb_inplace_xor */
1160 0, /* nb_inplace_or */
1161 (binaryfunc)complex_int_div, /* nb_floor_divide */
1162 (binaryfunc)complex_div, /* nb_true_divide */
1163 0, /* nb_inplace_floor_divide */
1164 0, /* nb_inplace_true_divide */
Guido van Rossumf9fca921996-01-12 00:47:05 +00001165};
1166
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001167PyTypeObject PyComplex_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001168 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossumf9fca921996-01-12 00:47:05 +00001169 "complex",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001170 sizeof(PyComplexObject),
Guido van Rossumf9fca921996-01-12 00:47:05 +00001171 0,
Georg Brandl347b3002006-03-30 11:57:00 +00001172 complex_dealloc, /* tp_dealloc */
Guido van Rossumbe4cbb12001-01-18 01:12:39 +00001173 (printfunc)complex_print, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001174 0, /* tp_getattr */
Guido van Rossumbe4cbb12001-01-18 01:12:39 +00001175 0, /* tp_setattr */
1176 0, /* tp_compare */
1177 (reprfunc)complex_repr, /* tp_repr */
1178 &complex_as_number, /* tp_as_number */
1179 0, /* tp_as_sequence */
1180 0, /* tp_as_mapping */
1181 (hashfunc)complex_hash, /* tp_hash */
1182 0, /* tp_call */
Tim Peters70695122001-03-11 08:37:29 +00001183 (reprfunc)complex_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001184 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossumbe4cbb12001-01-18 01:12:39 +00001185 0, /* tp_setattro */
1186 0, /* tp_as_buffer */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001187 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1188 complex_doc, /* tp_doc */
Guido van Rossumbe4cbb12001-01-18 01:12:39 +00001189 0, /* tp_traverse */
1190 0, /* tp_clear */
1191 complex_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001192 0, /* tp_weaklistoffset */
1193 0, /* tp_iter */
1194 0, /* tp_iternext */
1195 complex_methods, /* tp_methods */
1196 complex_members, /* tp_members */
1197 0, /* tp_getset */
1198 0, /* tp_base */
1199 0, /* tp_dict */
1200 0, /* tp_descr_get */
1201 0, /* tp_descr_set */
1202 0, /* tp_dictoffset */
1203 0, /* tp_init */
Georg Brandl6b50c632006-06-01 08:27:32 +00001204 PyType_GenericAlloc, /* tp_alloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001205 complex_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00001206 PyObject_Del, /* tp_free */
Guido van Rossumf9fca921996-01-12 00:47:05 +00001207};
1208
1209#endif