2 /* Complex object implementation */
4 /* Borrows heavily from floatobject.c */
6 /* Submitted by Jim Hugunin */
8 #ifndef WITHOUT_COMPLEX
12 /* Precisions used by repr() and str(), respectively.
14 The repr() precision (17 significant decimal digits) is the minimal number
15 that is guaranteed to have enough precision so that if the number is read
16 back in the exact same binary value is recreated. This is true for IEEE
17 floating point by design, and also happens to work for all other modern
20 The str() precision is chosen so that in most cases, the rounding noise
21 created by various operations is suppressed, while giving plenty of
22 precision for practical use.
28 /* elementary operations on complex numbers */
30 static Py_complex c_1
= {1., 0.};
33 c_sum(Py_complex a
, Py_complex b
)
36 r
.real
= a
.real
+ b
.real
;
37 r
.imag
= a
.imag
+ b
.imag
;
42 c_diff(Py_complex a
, Py_complex b
)
45 r
.real
= a
.real
- b
.real
;
46 r
.imag
= a
.imag
- b
.imag
;
60 c_prod(Py_complex a
, Py_complex b
)
63 r
.real
= a
.real
*b
.real
- a
.imag
*b
.imag
;
64 r
.imag
= a
.real
*b
.imag
+ a
.imag
*b
.real
;
69 c_quot(Py_complex a
, Py_complex b
)
71 /******************************************************************
72 This was the original algorithm. It's grossly prone to spurious
73 overflow and underflow errors. It also merrily divides by 0 despite
74 checking for that(!). The code still serves a doc purpose here, as
75 the algorithm following is a simple by-cases transformation of this
79 double d = b.real*b.real + b.imag*b.imag;
82 r.real = (a.real*b.real + a.imag*b.imag)/d;
83 r.imag = (a.imag*b.real - a.real*b.imag)/d;
85 ******************************************************************/
87 /* This algorithm is better, and is pretty obvious: first divide the
88 * numerators and denominator by whichever of {b.real, b.imag} has
89 * larger magnitude. The earliest reference I found was to CACM
90 * Algorithm 116 (Complex Division, Robert L. Smith, Stanford
91 * University). As usual, though, we're still ignoring all IEEE
94 Py_complex r
; /* the result */
95 const double abs_breal
= b
.real
< 0 ? -b
.real
: b
.real
;
96 const double abs_bimag
= b
.imag
< 0 ? -b
.imag
: b
.imag
;
98 if (abs_breal
>= abs_bimag
) {
99 /* divide tops and bottom by b.real */
100 if (abs_breal
== 0.0) {
102 r
.real
= r
.imag
= 0.0;
105 const double ratio
= b
.imag
/ b
.real
;
106 const double denom
= b
.real
+ b
.imag
* ratio
;
107 r
.real
= (a
.real
+ a
.imag
* ratio
) / denom
;
108 r
.imag
= (a
.imag
- a
.real
* ratio
) / denom
;
112 /* divide tops and bottom by b.imag */
113 const double ratio
= b
.real
/ b
.imag
;
114 const double denom
= b
.real
* ratio
+ b
.imag
;
115 assert(b
.imag
!= 0.0);
116 r
.real
= (a
.real
* ratio
+ a
.imag
) / denom
;
117 r
.imag
= (a
.imag
* ratio
- a
.real
) / denom
;
123 c_pow(Py_complex a
, Py_complex b
)
126 double vabs
,len
,at
,phase
;
127 if (b
.real
== 0. && b
.imag
== 0.) {
131 else if (a
.real
== 0. && a
.imag
== 0.) {
132 if (b
.imag
!= 0. || b
.real
< 0.)
138 vabs
= hypot(a
.real
,a
.imag
);
139 len
= pow(vabs
,b
.real
);
140 at
= atan2(a
.imag
, a
.real
);
143 len
/= exp(at
*b
.imag
);
144 phase
+= b
.imag
*log(vabs
);
146 r
.real
= len
*cos(phase
);
147 r
.imag
= len
*sin(phase
);
153 c_powu(Py_complex x
, long n
)
159 while (mask
> 0 && n
>= mask
) {
169 c_powi(Py_complex x
, long n
)
173 if (n
> 100 || n
< -100) {
174 cn
.real
= (double) n
;
181 return c_quot(c_1
,c_powu(x
,-n
));
186 PyComplex_FromCComplex(Py_complex cval
)
188 register PyComplexObject
*op
;
190 /* PyObject_New is inlined */
191 op
= (PyComplexObject
*) PyObject_MALLOC(sizeof(PyComplexObject
));
193 return PyErr_NoMemory();
194 PyObject_INIT(op
, &PyComplex_Type
);
196 return (PyObject
*) op
;
200 PyComplex_FromDoubles(double real
, double imag
)
205 return PyComplex_FromCComplex(c
);
209 PyComplex_RealAsDouble(PyObject
*op
)
211 if (PyComplex_Check(op
)) {
212 return ((PyComplexObject
*)op
)->cval
.real
;
215 return PyFloat_AsDouble(op
);
220 PyComplex_ImagAsDouble(PyObject
*op
)
222 if (PyComplex_Check(op
)) {
223 return ((PyComplexObject
*)op
)->cval
.imag
;
231 PyComplex_AsCComplex(PyObject
*op
)
234 if (PyComplex_Check(op
)) {
235 return ((PyComplexObject
*)op
)->cval
;
238 cv
.real
= PyFloat_AsDouble(op
);
245 complex_dealloc(PyObject
*op
)
252 complex_to_buf(char *buf
, PyComplexObject
*v
, int precision
)
254 if (v
->cval
.real
== 0.)
255 sprintf(buf
, "%.*gj", precision
, v
->cval
.imag
);
257 sprintf(buf
, "(%.*g%+.*gj)", precision
, v
->cval
.real
,
258 precision
, v
->cval
.imag
);
262 complex_print(PyComplexObject
*v
, FILE *fp
, int flags
)
265 complex_to_buf(buf
, v
,
266 (flags
& Py_PRINT_RAW
) ? PREC_STR
: PREC_REPR
);
272 complex_repr(PyComplexObject
*v
)
275 complex_to_buf(buf
, v
, PREC_REPR
);
276 return PyString_FromString(buf
);
280 complex_str(PyComplexObject
*v
)
283 complex_to_buf(buf
, v
, PREC_STR
);
284 return PyString_FromString(buf
);
288 complex_hash(PyComplexObject
*v
)
290 long hashreal
, hashimag
, combined
;
291 hashreal
= _Py_HashDouble(v
->cval
.real
);
294 hashimag
= _Py_HashDouble(v
->cval
.imag
);
297 /* Note: if the imaginary part is 0, hashimag is 0 now,
298 * so the following returns hashreal unchanged. This is
299 * important because numbers of different types that
300 * compare equal must have the same hash value, so that
301 * hash(x + 0*j) must equal hash(x).
303 combined
= hashreal
+ 1000003 * hashimag
;
310 complex_add(PyComplexObject
*v
, PyComplexObject
*w
)
313 PyFPE_START_PROTECT("complex_add", return 0)
314 result
= c_sum(v
->cval
,w
->cval
);
315 PyFPE_END_PROTECT(result
)
316 return PyComplex_FromCComplex(result
);
320 complex_sub(PyComplexObject
*v
, PyComplexObject
*w
)
323 PyFPE_START_PROTECT("complex_sub", return 0)
324 result
= c_diff(v
->cval
,w
->cval
);
325 PyFPE_END_PROTECT(result
)
326 return PyComplex_FromCComplex(result
);
330 complex_mul(PyComplexObject
*v
, PyComplexObject
*w
)
333 PyFPE_START_PROTECT("complex_mul", return 0)
334 result
= c_prod(v
->cval
,w
->cval
);
335 PyFPE_END_PROTECT(result
)
336 return PyComplex_FromCComplex(result
);
340 complex_div(PyComplexObject
*v
, PyComplexObject
*w
)
343 PyFPE_START_PROTECT("complex_div", return 0)
345 quot
= c_quot(v
->cval
,w
->cval
);
346 PyFPE_END_PROTECT(quot
)
348 PyErr_SetString(PyExc_ZeroDivisionError
, "complex division");
351 return PyComplex_FromCComplex(quot
);
355 complex_remainder(PyComplexObject
*v
, PyComplexObject
*w
)
359 div
= c_quot(v
->cval
,w
->cval
); /* The raw divisor value. */
361 PyErr_SetString(PyExc_ZeroDivisionError
, "complex remainder");
364 div
.real
= floor(div
.real
); /* Use the floor of the real part. */
366 mod
= c_diff(v
->cval
, c_prod(w
->cval
, div
));
368 return PyComplex_FromCComplex(mod
);
373 complex_divmod(PyComplexObject
*v
, PyComplexObject
*w
)
378 div
= c_quot(v
->cval
,w
->cval
); /* The raw divisor value. */
380 PyErr_SetString(PyExc_ZeroDivisionError
, "complex divmod()");
383 div
.real
= floor(div
.real
); /* Use the floor of the real part. */
385 mod
= c_diff(v
->cval
, c_prod(w
->cval
, div
));
386 d
= PyComplex_FromCComplex(div
);
387 m
= PyComplex_FromCComplex(mod
);
388 z
= Py_BuildValue("(OO)", d
, m
);
395 complex_pow(PyComplexObject
*v
, PyObject
*w
, PyComplexObject
*z
)
401 if ((PyObject
*)z
!=Py_None
) {
402 PyErr_SetString(PyExc_ValueError
, "complex modulo");
405 PyFPE_START_PROTECT("complex_pow", return 0)
407 exponent
= ((PyComplexObject
*)w
)->cval
;
408 int_exponent
= (long)exponent
.real
;
409 if (exponent
.imag
== 0. && exponent
.real
== int_exponent
)
410 p
= c_powi(v
->cval
,int_exponent
);
412 p
= c_pow(v
->cval
,exponent
);
415 if (errno
== ERANGE
) {
416 PyErr_SetString(PyExc_ValueError
,
417 "0.0 to a negative or complex power");
420 return PyComplex_FromCComplex(p
);
424 complex_neg(PyComplexObject
*v
)
427 neg
.real
= -v
->cval
.real
;
428 neg
.imag
= -v
->cval
.imag
;
429 return PyComplex_FromCComplex(neg
);
433 complex_pos(PyComplexObject
*v
)
436 return (PyObject
*)v
;
440 complex_abs(PyComplexObject
*v
)
443 PyFPE_START_PROTECT("complex_abs", return 0)
444 result
= hypot(v
->cval
.real
,v
->cval
.imag
);
445 PyFPE_END_PROTECT(result
)
446 return PyFloat_FromDouble(result
);
450 complex_nonzero(PyComplexObject
*v
)
452 return v
->cval
.real
!= 0.0 || v
->cval
.imag
!= 0.0;
456 complex_coerce(PyObject
**pv
, PyObject
**pw
)
460 if (PyInt_Check(*pw
)) {
461 cval
.real
= (double)PyInt_AsLong(*pw
);
462 *pw
= PyComplex_FromCComplex(cval
);
466 else if (PyLong_Check(*pw
)) {
467 cval
.real
= PyLong_AsDouble(*pw
);
468 *pw
= PyComplex_FromCComplex(cval
);
472 else if (PyFloat_Check(*pw
)) {
473 cval
.real
= PyFloat_AsDouble(*pw
);
474 *pw
= PyComplex_FromCComplex(cval
);
478 return 1; /* Can't do it */
482 complex_richcompare(PyObject
*v
, PyObject
*w
, int op
)
488 if (op
!= Py_EQ
&& op
!= Py_NE
) {
489 PyErr_SetString(PyExc_TypeError
,
490 "cannot compare complex numbers using <, <=, >, >=");
494 c
= PyNumber_CoerceEx(&v
, &w
);
498 Py_INCREF(Py_NotImplemented
);
499 return Py_NotImplemented
;
501 if (!PyComplex_Check(v
) || !PyComplex_Check(w
)) {
504 Py_INCREF(Py_NotImplemented
);
505 return Py_NotImplemented
;
508 i
= ((PyComplexObject
*)v
)->cval
;
509 j
= ((PyComplexObject
*)w
)->cval
;
513 if ((i
.real
== j
.real
&& i
.imag
== j
.imag
) == (op
== Py_EQ
))
523 complex_int(PyObject
*v
)
525 PyErr_SetString(PyExc_TypeError
,
526 "can't convert complex to int; use e.g. int(abs(z))");
531 complex_long(PyObject
*v
)
533 PyErr_SetString(PyExc_TypeError
,
534 "can't convert complex to long; use e.g. long(abs(z))");
539 complex_float(PyObject
*v
)
541 PyErr_SetString(PyExc_TypeError
,
542 "can't convert complex to float; use e.g. abs(z)");
547 complex_conjugate(PyObject
*self
, PyObject
*args
)
550 if (!PyArg_ParseTuple(args
, ":conjugate"))
552 c
= ((PyComplexObject
*)self
)->cval
;
554 return PyComplex_FromCComplex(c
);
557 static PyMethodDef complex_methods
[] = {
558 {"conjugate", complex_conjugate
, 1},
559 {NULL
, NULL
} /* sentinel */
564 complex_getattr(PyComplexObject
*self
, char *name
)
566 if (strcmp(name
, "real") == 0)
567 return (PyObject
*)PyFloat_FromDouble(self
->cval
.real
);
568 else if (strcmp(name
, "imag") == 0)
569 return (PyObject
*)PyFloat_FromDouble(self
->cval
.imag
);
570 else if (strcmp(name
, "__members__") == 0)
571 return Py_BuildValue("[ss]", "imag", "real");
572 return Py_FindMethod(complex_methods
, (PyObject
*)self
, name
);
575 static PyNumberMethods complex_as_number
= {
576 (binaryfunc
)complex_add
, /* nb_add */
577 (binaryfunc
)complex_sub
, /* nb_subtract */
578 (binaryfunc
)complex_mul
, /* nb_multiply */
579 (binaryfunc
)complex_div
, /* nb_divide */
580 (binaryfunc
)complex_remainder
, /* nb_remainder */
581 (binaryfunc
)complex_divmod
, /* nb_divmod */
582 (ternaryfunc
)complex_pow
, /* nb_power */
583 (unaryfunc
)complex_neg
, /* nb_negative */
584 (unaryfunc
)complex_pos
, /* nb_positive */
585 (unaryfunc
)complex_abs
, /* nb_absolute */
586 (inquiry
)complex_nonzero
, /* nb_nonzero */
593 (coercion
)complex_coerce
, /* nb_coerce */
594 (unaryfunc
)complex_int
, /* nb_int */
595 (unaryfunc
)complex_long
, /* nb_long */
596 (unaryfunc
)complex_float
, /* nb_float */
601 PyTypeObject PyComplex_Type
= {
602 PyObject_HEAD_INIT(&PyType_Type
)
605 sizeof(PyComplexObject
),
607 (destructor
)complex_dealloc
, /* tp_dealloc */
608 (printfunc
)complex_print
, /* tp_print */
609 (getattrfunc
)complex_getattr
, /* tp_getattr */
612 (reprfunc
)complex_repr
, /* tp_repr */
613 &complex_as_number
, /* tp_as_number */
614 0, /* tp_as_sequence */
615 0, /* tp_as_mapping */
616 (hashfunc
)complex_hash
, /* tp_hash */
618 (reprfunc
)complex_str
, /* tp_str */
621 0, /* tp_as_buffer */
622 Py_TPFLAGS_DEFAULT
, /* tp_flags */
626 complex_richcompare
, /* tp_richcompare */