complexobject.c 32 KB

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