Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagesmc
Path: blob/master/src/sage/rings/complex_number.pyx
8817 views
1
"""
2
Arbitrary Precision Complex Numbers
3
4
AUTHORS:
5
6
- William Stein (2006-01-26): complete rewrite
7
8
- Joel B. Mohler (2006-12-16): naive rewrite into pyrex
9
10
- William Stein(2007-01): rewrite of Mohler's rewrite
11
12
- Vincent Delecroix (2010-01): plot function
13
14
- Travis Scrimshaw (2012-10-18): Added documentation for full coverage
15
"""
16
17
#*****************************************************************************
18
# Copyright (C) 2006 William Stein <[email protected]>
19
#
20
# Distributed under the terms of the GNU General Public License (GPL)
21
# as published by the Free Software Foundation; either version 2 of
22
# the License, or (at your option) any later version.
23
# http://www.gnu.org/licenses/
24
#*****************************************************************************
25
26
27
import math
28
import operator
29
30
from sage.structure.element cimport FieldElement, RingElement, Element, ModuleElement
31
from sage.categories.map cimport Map
32
33
from complex_double cimport ComplexDoubleElement
34
from real_mpfr cimport RealNumber
35
36
import complex_field
37
import sage.misc.misc
38
import integer
39
import infinity
40
41
from sage.libs.mpmath.utils cimport mpfr_to_mpfval
42
43
include "sage/ext/stdsage.pxi"
44
45
cdef object numpy_complex_interface = {'typestr': '=c16'}
46
cdef object numpy_object_interface = {'typestr': '|O'}
47
48
cdef mp_rnd_t rnd
49
rnd = GMP_RNDN
50
51
cdef double LOG_TEN_TWO_PLUS_EPSILON = 3.321928094887363 # a small overestimate of log(10,2)
52
53
def set_global_complex_round_mode(n):
54
"""
55
Set the global complex rounding mode.
56
57
.. WARNING::
58
59
Do not call this function explicitly. The default rounding mode is
60
``n = 0``.
61
62
EXAMPLES::
63
64
sage: sage.rings.complex_number.set_global_complex_round_mode(0)
65
"""
66
global rnd
67
rnd = n
68
69
#from sage.databases.odlyzko import zeta_zeroes
70
71
def is_ComplexNumber(x):
72
r"""
73
Returns ``True`` if ``x`` is a complex number. In particular, if ``x`` is
74
of the :class:`ComplexNumber` type.
75
76
EXAMPLES::
77
78
sage: from sage.rings.complex_number import is_ComplexNumber
79
sage: a = ComplexNumber(1,2); a
80
1.00000000000000 + 2.00000000000000*I
81
sage: is_ComplexNumber(a)
82
True
83
sage: b = ComplexNumber(1); b
84
1.00000000000000
85
sage: is_ComplexNumber(b)
86
True
87
88
Note that the global element ``I`` is of type :class:`SymbolicConstant`.
89
However, elements of the class :class:`ComplexField_class` are of type
90
:class:`ComplexNumber`::
91
92
sage: c = 1 + 2*I
93
sage: is_ComplexNumber(c)
94
False
95
sage: d = CC(1 + 2*I)
96
sage: is_ComplexNumber(d)
97
True
98
"""
99
return isinstance(x, ComplexNumber)
100
101
cdef class ComplexNumber(sage.structure.element.FieldElement):
102
"""
103
A floating point approximation to a complex number using any
104
specified precision. Answers derived from calculations with such
105
approximations may differ from what they would be if those
106
calculations were performed with true complex numbers. This is due
107
to the rounding errors inherent to finite precision calculations.
108
109
EXAMPLES::
110
111
sage: I = CC.0
112
sage: b = 1.5 + 2.5*I
113
sage: loads(b.dumps()) == b
114
True
115
"""
116
117
cdef ComplexNumber _new(self):
118
"""
119
Quickly creates a new initialized complex number with the same
120
parent as ``self``.
121
"""
122
cdef ComplexNumber x
123
x = PY_NEW(ComplexNumber)
124
x._parent = self._parent
125
x._prec = self._prec
126
x._multiplicative_order = None
127
mpfr_init2(x.__re, self._prec)
128
mpfr_init2(x.__im, self._prec)
129
return x
130
131
def __cinit__(self, parent=None, real=None, imag=None):
132
"""
133
Cython initialize ``self``.
134
135
EXAMPLES::
136
137
sage: ComplexNumber(2,1) # indirect doctest
138
2.00000000000000 + 1.00000000000000*I
139
"""
140
self._prec = -1
141
142
def __init__(self, parent, real, imag=None):
143
r"""
144
Initialize :class:`ComplexNumber` instance.
145
146
EXAMPLES::
147
148
sage: a = ComplexNumber(2,1)
149
sage: a.__init__(CC,2,1)
150
sage: a
151
2.00000000000000 + 1.00000000000000*I
152
sage: parent(a)
153
Complex Field with 53 bits of precision
154
sage: real(a)
155
2.00000000000000
156
sage: imag(a)
157
1.00000000000000
158
"""
159
cdef real_mpfr.RealNumber rr, ii
160
self._parent = parent
161
self._prec = self._parent._prec
162
self._multiplicative_order = None
163
164
mpfr_init2(self.__re, self._prec)
165
mpfr_init2(self.__im, self._prec)
166
167
if imag is None:
168
if real is None: return
169
170
if PY_TYPE_CHECK(real, ComplexNumber):
171
real, imag = (<ComplexNumber>real).real(), (<ComplexNumber>real).imag()
172
elif isinstance(real, sage.libs.pari.all.pari_gen):
173
real, imag = real.real(), real.imag()
174
elif isinstance(real, list) or isinstance(real, tuple):
175
re, imag = real
176
real = re
177
elif isinstance(real, complex):
178
real, imag = real.real, real.imag
179
else:
180
imag = 0
181
try:
182
R = parent._real_field()
183
rr = R(real)
184
ii = R(imag)
185
mpfr_set(self.__re, rr.value, rnd)
186
mpfr_set(self.__im, ii.value, rnd)
187
except TypeError:
188
raise TypeError, "unable to coerce to a ComplexNumber: %s" % type(real)
189
190
191
def __dealloc__(self):
192
"""
193
TESTS:
194
195
Check that :trac:`12038` is resolved::
196
197
sage: from sage.rings.complex_number import ComplexNumber as CN
198
sage: coerce(CN, 1+I)
199
Traceback (most recent call last):
200
...
201
TypeError: __init__() takes at least 2 positional arguments (1 given)
202
"""
203
if self._prec != -1:
204
mpfr_clear(self.__re)
205
mpfr_clear(self.__im)
206
207
def _interface_init_(self, I=None):
208
"""
209
Returns ``self`` formatted as a string, suitable as input to another
210
computer algebra system. (This is the default function used for
211
exporting to other computer algebra systems.)
212
213
EXAMPLES::
214
215
sage: s1 = CC(exp(I)); s1
216
0.540302305868140 + 0.841470984807897*I
217
sage: s1._interface_init_()
218
'0.54030230586813977 + 0.84147098480789650*I'
219
sage: s1 == CC(gp(s1))
220
True
221
"""
222
return self.str(truncate=False)
223
224
def _maxima_init_(self, I=None):
225
"""
226
Return a string representation of this complex number in the syntax of
227
Maxima. That is, use ``%i`` to represent the complex unit.
228
229
EXAMPLES::
230
231
sage: CC.0._maxima_init_()
232
'1.0000000000000000*%i'
233
sage: CC(.5 + I)._maxima_init_()
234
'0.50000000000000000 + 1.0000000000000000*%i'
235
"""
236
return self.str(truncate=False, istr='%i')
237
238
property __array_interface__:
239
def __get__(self):
240
"""
241
Used for NumPy conversion.
242
243
EXAMPLES::
244
245
sage: import numpy
246
sage: numpy.array([1.0, 2.5j]).dtype
247
dtype('complex128')
248
sage: numpy.array([1.000000000000000000000000000000000000j]).dtype
249
dtype('O')
250
"""
251
if self._prec <= 57: # max size of repr(float)
252
return numpy_complex_interface
253
else:
254
return numpy_object_interface
255
256
def _sage_input_(self, sib, coerced):
257
r"""
258
Produce an expression which will reproduce this value when evaluated.
259
260
EXAMPLES::
261
262
sage: for prec in (2, 53, 200):
263
... fld = ComplexField(prec)
264
... var = polygen(fld)
265
... ins = [-20, 0, 1, -2^4000, 2^-4000] + [fld._real_field().random_element() for _ in range(3)]
266
... for v1 in ins:
267
... for v2 in ins:
268
... v = fld(v1, v2)
269
... _ = sage_input(fld(v), verify=True)
270
... _ = sage_input(fld(v) * var, verify=True)
271
sage: x = polygen(CC)
272
sage: for v1 in [-2, 0, 2]:
273
... for v2 in [-2, -1, 0, 1, 2]:
274
... print str(sage_input(x + CC(v1, v2))).splitlines()[1]
275
x + CC(-2 - RR(2)*I)
276
x + CC(-2 - RR(1)*I)
277
x - 2
278
x + CC(-2 + RR(1)*I)
279
x + CC(-2 + RR(2)*I)
280
x - CC(RR(2)*I)
281
x - CC(RR(1)*I)
282
x
283
x + CC(RR(1)*I)
284
x + CC(RR(2)*I)
285
x + CC(2 - RR(2)*I)
286
x + CC(2 - RR(1)*I)
287
x + 2
288
x + CC(2 + RR(1)*I)
289
x + CC(2 + RR(2)*I)
290
sage: from sage.misc.sage_input import SageInputBuilder
291
sage: sib = SageInputBuilder()
292
sage: sib_np = SageInputBuilder(preparse=False)
293
sage: CC(-infinity)._sage_input_(sib, True)
294
{unop:- {call: {atomic:RR}({atomic:Infinity})}}
295
sage: CC(0, infinity)._sage_input_(sib, True)
296
{call: {atomic:CC}({call: {atomic:RR}({atomic:0})}, {call: {atomic:RR}({atomic:Infinity})})}
297
sage: CC(NaN, 5)._sage_input_(sib, True)
298
{call: {atomic:CC}({call: {atomic:RR}({atomic:NaN})}, {call: {atomic:RR}({atomic:5})})}
299
sage: CC(5, NaN)._sage_input_(sib, True)
300
{call: {atomic:CC}({call: {atomic:RR}({atomic:5})}, {call: {atomic:RR}({atomic:NaN})})}
301
sage: CC(12345)._sage_input_(sib, True)
302
{atomic:12345}
303
sage: CC(-12345)._sage_input_(sib, False)
304
{call: {atomic:CC}({binop:+ {unop:- {atomic:12345}} {binop:* {call: {atomic:RR}({atomic:0})} {atomic:I}}})}
305
sage: CC(0, 12345)._sage_input_(sib, True)
306
{call: {atomic:CC}({binop:* {call: {atomic:RR}({atomic:12345})} {atomic:I}})}
307
sage: CC(0, -12345)._sage_input_(sib, False)
308
{unop:- {call: {atomic:CC}({binop:* {call: {atomic:RR}({atomic:12345})} {atomic:I}})}}
309
sage: CC(1.579)._sage_input_(sib, True)
310
{atomic:1.579}
311
sage: CC(1.579)._sage_input_(sib_np, True)
312
{atomic:1.579}
313
sage: ComplexField(150).zeta(37)._sage_input_(sib, True)
314
{call: {call: {atomic:ComplexField}({atomic:150})}({binop:+ {atomic:0.98561591034770846226477029397621845736859851519} {binop:* {call: {call: {atomic:RealField}({atomic:150})}({atomic:0.16900082032184907409303555538443060626072476297})} {atomic:I}}})}
315
sage: ComplexField(150).zeta(37)._sage_input_(sib_np, True)
316
{call: {call: {atomic:ComplexField}({atomic:150})}({binop:+ {call: {call: {atomic:RealField}({atomic:150})}({atomic:'0.98561591034770846226477029397621845736859851519'})} {binop:* {call: {call: {atomic:RealField}({atomic:150})}({atomic:'0.16900082032184907409303555538443060626072476297'})} {atomic:I}}})}
317
"""
318
if coerced and self.imag() == 0:
319
return sib(self.real(), True)
320
321
# The body will be coerced first to symbolics and then to CC.
322
# This works fine if we produce integer or float literals, but
323
# not for infinity or NaN.
324
if not (mpfr_number_p(self.__re) and mpfr_number_p(self.__im)):
325
return sib(self.parent())(self.real(), self.imag())
326
327
# The following uses of .sum() and .prod() will simplify
328
# 3+0*I to 3, 0+1*I to I, etc.
329
real_part = sib(self.real(), 2)
330
imag_part = sib.prod([sib(self.imag()), sib.name('I')],
331
simplify=True)
332
sum = sib.sum([real_part, imag_part], simplify=True)
333
if sum._sie_is_negation():
334
return -sib(self.parent())(sum._sie_operand)
335
else:
336
return sib(self.parent())(sum)
337
338
# The following is an (untested) implementation that produces
339
# CC_I = CC.gen()
340
# 2 + 3*CC_I
341
# instead of CC(2 + 3*I)
342
# cdef int prec
343
344
# if self.real().is_zero() and self.imag() == 1:
345
# v = sib(self.parent()).gen()
346
# prec = self.prec()
347
# if prec == 53:
348
# gen_name = 'CC_I'
349
# else:
350
# gen_name = 'CC%d_I' % prec
351
# sib.cache(self, v, gen_name)
352
353
# real_part = sib(self.real())
354
# imag_part = sib.prod([self.imag(), self.parent().gen()], simplify=True)
355
# return sib.sum([real_part, imag_part], simplify=True)
356
357
def _repr_(self):
358
r"""
359
Returns ``self`` formatted as a string.
360
361
EXAMPLES::
362
363
sage: a = ComplexNumber(2,1); a
364
2.00000000000000 + 1.00000000000000*I
365
sage: a._repr_()
366
'2.00000000000000 + 1.00000000000000*I'
367
"""
368
return self.str(10)
369
370
def __hash__(self):
371
"""
372
Returns the hash of ``self``, which coincides with the python complex
373
and float (and often int) types.
374
375
This has the drawback that two very close high precision numbers
376
will have the same hash, but allows them to play nicely with other
377
real types.
378
379
EXAMPLES::
380
381
sage: hash(CC(1.2, 33)) == hash(complex(1.2, 33))
382
True
383
"""
384
return hash(complex(self))
385
386
def __getitem__(self, i):
387
r"""
388
Returns either the real or imaginary component of self depending on
389
the choice of i: real (i=0), imaginary (i=1)
390
391
INPUTS:
392
393
- ``i`` - 0 or 1
394
- ``0`` -- will return the real component of ``self``
395
- ``1`` -- will return the imaginary component of ``self``
396
397
EXAMPLES::
398
399
sage: a = ComplexNumber(2,1)
400
sage: a.__getitem__(0)
401
2.00000000000000
402
sage: a.__getitem__(1)
403
1.00000000000000
404
405
::
406
407
sage: b = CC(42,0)
408
sage: b
409
42.0000000000000
410
sage: b.__getitem__(1)
411
0.000000000000000
412
"""
413
if i == 0:
414
return self.real()
415
elif i == 1:
416
return self.imag()
417
raise IndexError, "i must be between 0 and 1."
418
419
def __reduce__( self ):
420
"""
421
Pickling support
422
423
EXAMPLES::
424
425
sage: a = CC(1 + I)
426
sage: loads(dumps(a)) == a
427
True
428
"""
429
# TODO: This is potentially slow -- make a 1 version that
430
# is native and much faster -- doesn't use .real()/.imag()
431
return (make_ComplexNumber0, (self._parent, self._multiplicative_order, self.real(), self.imag()))
432
433
def _set_multiplicative_order(self, n):
434
r"""
435
Function for setting the attribute :meth:`multiplicative_order` of
436
``self``.
437
438
.. WARNING::
439
440
It is not advisable to explicitly call
441
``_set_multiplicative_order()`` for explicitly declared complex
442
numbers.
443
444
INPUT:
445
446
- ``n`` -- an integer which will define the multiplicative order
447
448
EXAMPLES::
449
450
sage: a = ComplexNumber(2,1)
451
sage: a.multiplicative_order()
452
+Infinity
453
sage: a._set_multiplicative_order(5)
454
sage: a.multiplicative_order()
455
5
456
sage: a^5
457
-38.0000000000000 + 41.0000000000000*I
458
"""
459
self._multiplicative_order = integer.Integer(n)
460
461
def str(self, base=10, truncate=True, istr='I'):
462
r"""
463
Return a string representation of ``self``.
464
465
INPUTS:
466
467
- ``base`` -- (Default: 10) The base to use for printing
468
469
- ``truncate`` -- (Default: ``True``) Whether to print fewer
470
digits than are available, to mask errors in the last bits.
471
472
- ``istr`` -- (Default: ``I``) String representation of the complex unit
473
474
EXAMPLES::
475
476
sage: a = CC(pi + I*e)
477
sage: a.str()
478
'3.14159265358979 + 2.71828182845905*I'
479
sage: a.str(truncate=False)
480
'3.1415926535897931 + 2.7182818284590451*I'
481
sage: a.str(base=2)
482
'11.001001000011111101101010100010001000010110100011000 + 10.101101111110000101010001011000101000101011101101001*I'
483
sage: CC(0.5 + 0.625*I).str(base=2)
484
'0.10000000000000000000000000000000000000000000000000000 + 0.10100000000000000000000000000000000000000000000000000*I'
485
sage: a.str(base=16)
486
'3.243f6a8885a30 + 2.b7e151628aed2*I'
487
sage: a.str(base=36)
488
'3.53i5ab8p5fc + 2.puw5nggjf8f*I'
489
sage: CC(0)
490
0.000000000000000
491
sage: CC.0.str(istr='%i')
492
'1.00000000000000*%i'
493
"""
494
s = ""
495
if self.real() != 0:
496
s = self.real().str(base, truncate=truncate)
497
if self.imag() != 0:
498
y = self.imag()
499
if s!="":
500
if y < 0:
501
s = s+" - "
502
y = -y
503
else:
504
s = s+" + "
505
s = s+"{ystr}*{istr}".format(ystr=y.str(base, truncate=truncate),
506
istr=istr)
507
if len(s) == 0:
508
s = self.real().str(base, truncate=truncate)
509
return s
510
511
def _latex_(self):
512
r"""
513
Method for converting ``self`` to a string with latex formatting.
514
Called by the global function ``latex``.
515
516
EXAMPLES::
517
518
sage: a = ComplexNumber(2,1)
519
sage: a
520
2.00000000000000 + 1.00000000000000*I
521
sage: latex(a)
522
2.00000000000000 + 1.00000000000000i
523
sage: a._latex_()
524
'2.00000000000000 + 1.00000000000000i'
525
526
::
527
528
sage: b = ComplexNumber(7,4,min_prec=16)
529
sage: b
530
7.000 + 4.000*I
531
sage: latex(b)
532
7.000 + 4.000i
533
sage: b._latex_()
534
'7.000 + 4.000i'
535
536
::
537
538
sage: ComplexNumber(0).log()._latex_()
539
'-\\infty'
540
"""
541
import re
542
s = self.str().replace('*I', 'i').replace('infinity','\\infty')
543
return re.sub(r"e(-?\d+)", r" \\times 10^{\1}", s)
544
545
def _pari_(self):
546
r"""
547
Coerces ``self`` into a Pari ``complex`` object.
548
549
EXAMPLES:
550
551
Coerce the object using the ``pari`` function::
552
553
sage: a = ComplexNumber(2,1)
554
sage: pari(a)
555
2.00000000000000 + 1.00000000000000*I
556
sage: type(pari(a))
557
<type 'sage.libs.pari.gen.gen'>
558
sage: a._pari_()
559
2.00000000000000 + 1.00000000000000*I
560
sage: type(a._pari_())
561
<type 'sage.libs.pari.gen.gen'>
562
"""
563
return sage.libs.pari.all.pari.complex(self.real()._pari_(), self.imag()._pari_())
564
565
def _mpmath_(self, prec=None, rounding=None):
566
"""
567
Returns an mpmath version of ``self``.
568
569
.. NOTE::
570
571
Currently, the rounding mode is ignored.
572
573
EXAMPLES::
574
575
sage: CC(1,2)._mpmath_()
576
mpc(real='1.0', imag='2.0')
577
"""
578
if prec is not None:
579
return self.n(prec=prec)._mpmath_()
580
from sage.libs.mpmath.all import make_mpc
581
re = mpfr_to_mpfval(self.__re)
582
im = mpfr_to_mpfval(self.__im)
583
return make_mpc((re, im))
584
585
cpdef ModuleElement _add_(self, ModuleElement right):
586
"""
587
Add ``self`` to ``right``.
588
589
EXAMPLES::
590
591
sage: CC(2, 1)._add_(CC(1, -2))
592
3.00000000000000 - 1.00000000000000*I
593
"""
594
cdef ComplexNumber x
595
x = self._new()
596
mpfr_add(x.__re, self.__re, (<ComplexNumber>right).__re, rnd)
597
mpfr_add(x.__im, self.__im, (<ComplexNumber>right).__im, rnd)
598
return x
599
600
cpdef ModuleElement _sub_(self, ModuleElement right):
601
"""
602
Subtract ``right`` from ``self``.
603
604
EXAMPLES::
605
606
sage: CC(2, 1)._sub_(CC(1, -2))
607
1.00000000000000 + 3.00000000000000*I
608
"""
609
cdef ComplexNumber x
610
x = self._new()
611
mpfr_sub(x.__re, self.__re, (<ComplexNumber>right).__re, rnd)
612
mpfr_sub(x.__im, self.__im, (<ComplexNumber>right).__im, rnd)
613
return x
614
615
cpdef RingElement _mul_(self, RingElement right):
616
"""
617
Multiply ``self`` by ``right``.
618
619
EXAMPLES::
620
621
sage: CC(2, 1)._mul_(CC(1, -2))
622
4.00000000000000 - 3.00000000000000*I
623
"""
624
cdef ComplexNumber x
625
x = self._new()
626
cdef mpfr_t t0, t1
627
mpfr_init2(t0, self._prec)
628
mpfr_init2(t1, self._prec)
629
mpfr_mul(t0, self.__re, (<ComplexNumber>right).__re, rnd)
630
mpfr_mul(t1, self.__im, (<ComplexNumber>right).__im, rnd)
631
mpfr_sub(x.__re, t0, t1, rnd)
632
mpfr_mul(t0, self.__re, (<ComplexNumber>right).__im, rnd)
633
mpfr_mul(t1, self.__im, (<ComplexNumber>right).__re, rnd)
634
mpfr_add(x.__im, t0, t1, rnd)
635
mpfr_clear(t0)
636
mpfr_clear(t1)
637
return x
638
639
def norm(self):
640
r"""
641
Returns the norm of this complex number.
642
643
If `c = a + bi` is a complex number, then the norm of `c` is defined as
644
the product of `c` and its complex conjugate:
645
646
.. MATH::
647
648
\text{norm}(c)
649
=
650
\text{norm}(a + bi)
651
=
652
c \cdot \overline{c}
653
=
654
a^2 + b^2.
655
656
The norm of a complex number is different from its absolute value.
657
The absolute value of a complex number is defined to be the square
658
root of its norm. A typical use of the complex norm is in the
659
integral domain `\ZZ[i]` of Gaussian integers, where the norm of
660
each Gaussian integer `c = a + bi` is defined as its complex norm.
661
662
.. SEEALSO::
663
664
- :func:`sage.misc.functional.norm`
665
666
- :meth:`sage.rings.complex_double.ComplexDoubleElement.norm`
667
668
EXAMPLES:
669
670
This indeed acts as the square function when the
671
imaginary component of ``self`` is equal to zero::
672
673
sage: a = ComplexNumber(2,1)
674
sage: a.norm()
675
5.00000000000000
676
sage: b = ComplexNumber(4.2,0)
677
sage: b.norm()
678
17.6400000000000
679
sage: b^2
680
17.6400000000000
681
"""
682
return self.norm_c()
683
684
cdef real_mpfr.RealNumber norm_c(ComplexNumber self):
685
cdef real_mpfr.RealNumber x
686
x = real_mpfr.RealNumber(self._parent._real_field(), None)
687
688
cdef mpfr_t t0, t1
689
mpfr_init2(t0, self._prec)
690
mpfr_init2(t1, self._prec)
691
692
mpfr_mul(t0, self.__re, self.__re, rnd)
693
mpfr_mul(t1, self.__im, self.__im, rnd)
694
695
mpfr_add(x.value, t0, t1, rnd)
696
697
mpfr_clear(t0)
698
mpfr_clear(t1)
699
return x
700
701
cdef real_mpfr.RealNumber abs_c(ComplexNumber self):
702
cdef real_mpfr.RealNumber x
703
x = real_mpfr.RealNumber(self._parent._real_field(), None)
704
705
cdef mpfr_t t0, t1
706
mpfr_init2(t0, self._prec)
707
mpfr_init2(t1, self._prec)
708
709
mpfr_mul(t0, self.__re, self.__re, rnd)
710
mpfr_mul(t1, self.__im, self.__im, rnd)
711
712
mpfr_add(x.value, t0, t1, rnd)
713
mpfr_sqrt(x.value, x.value, rnd)
714
715
mpfr_clear(t0)
716
mpfr_clear(t1)
717
return x
718
719
cpdef RingElement _div_(self, RingElement right):
720
"""
721
Divide ``self`` by ``right``.
722
723
EXAMPLES::
724
725
sage: CC(2, 1)._div_(CC(1, -2))
726
1.00000000000000*I
727
"""
728
cdef ComplexNumber x
729
x = self._new()
730
cdef mpfr_t a, b, t0, t1, right_nm
731
mpfr_init2(t0, self._prec)
732
mpfr_init2(t1, self._prec)
733
mpfr_init2(a, self._prec)
734
mpfr_init2(b, self._prec)
735
mpfr_init2(right_nm, self._prec)
736
737
mpfr_mul(t0, (<ComplexNumber>right).__re, (<ComplexNumber>right).__re, rnd)
738
mpfr_mul(t1, (<ComplexNumber>right).__im, (<ComplexNumber>right).__im, rnd)
739
mpfr_add(right_nm, t0, t1, rnd)
740
741
mpfr_div(a, (<ComplexNumber>right).__re, right_nm, rnd)
742
mpfr_div(b, (<ComplexNumber>right).__im, right_nm, rnd)
743
744
## Do this: x.__re = a * self.__re + b * self.__im
745
mpfr_mul(t0, a, self.__re, rnd)
746
mpfr_mul(t1, b, self.__im, rnd)
747
mpfr_add(x.__re, t0, t1, rnd)
748
749
## Do this: x.__im = a * self.__im - b * self.__re
750
mpfr_mul(t0, a, self.__im, rnd)
751
mpfr_mul(t1, b, self.__re, rnd)
752
mpfr_sub(x.__im, t0, t1, rnd)
753
mpfr_clear(t0)
754
mpfr_clear(t1)
755
mpfr_clear(a)
756
mpfr_clear(b)
757
mpfr_clear(right_nm)
758
return x
759
760
def __rdiv__(self, left):
761
r"""
762
Returns the quotient of left with ``self``, that is:
763
764
``left/self``
765
766
as a complex number.
767
768
INPUT:
769
770
- ``left`` - a complex number to divide by ``self``
771
772
EXAMPLES::
773
774
sage: a = ComplexNumber(2,0)
775
sage: a.__rdiv__(CC(1))
776
0.500000000000000
777
sage: CC(1)/a
778
0.500000000000000
779
"""
780
return ComplexNumber(self._parent, left)/self
781
782
def __pow__(self, right, modulus):
783
r"""
784
Raise ``self`` to the ``right`` expontent.
785
786
This takes `a^b` and compues `\exp(b \log(a))`.
787
788
EXAMPLES::
789
790
sage: C.<i> = ComplexField(20)
791
sage: a = i^2; a
792
-1.0000
793
sage: a.parent()
794
Complex Field with 20 bits of precision
795
sage: a = (1+i)^i; a
796
0.42883 + 0.15487*I
797
sage: (1+i)^(1+i)
798
0.27396 + 0.58370*I
799
sage: a.parent()
800
Complex Field with 20 bits of precision
801
sage: i^i
802
0.20788
803
sage: (2+i)^(0.5)
804
1.4553 + 0.34356*I
805
"""
806
if isinstance(right, (int, long, integer.Integer)):
807
return sage.rings.ring_element.RingElement.__pow__(self, right)
808
809
try:
810
return (self.log()*right).exp()
811
except TypeError:
812
pass
813
814
try:
815
self = right.parent()(self)
816
return self**right
817
except AttributeError:
818
raise TypeError
819
820
def _magma_init_(self, magma):
821
r"""
822
EXAMPLES::
823
824
sage: magma(CC([1, 2])) # indirect doctest, optional - magma
825
1.00000000000000 + 2.00000000000000*$.1
826
sage: v = magma(CC([1, 2])).sage(); v # indirect, optional - magma
827
1.00000000000000 + 2.00000000000000*I
828
sage: v.parent() # optional - magma
829
Complex Field with 53 bits of precision
830
831
sage: i = ComplexField(200).gen()
832
sage: sqrt(i)
833
0.70710678118654752440084436210484903928483593768847403658834 + 0.70710678118654752440084436210484903928483593768847403658834*I
834
sage: magma(sqrt(i)) # indirect, optional - magma
835
0.707106781186547524400844362104849039284835937688474036588340 + 0.707106781186547524400844362104849039284835937688474036588340*$.1
836
sage: magma(i).Sqrt() # indirect, optional - magma
837
0.707106781186547524400844362104849039284835937688474036588340 + 0.707106781186547524400844362104849039284835937688474036588340*$.1
838
839
sage: magma(ComplexField(200)(1/3)) # indirect, optional - magma
840
0.333333333333333333333333333333333333333333333333333333333333
841
"""
842
real_string = self.real().str(truncate=False)
843
imag_string = self.imag().str(truncate=False)
844
digit_precision_bound = len(real_string)
845
return "%s![%sp%s, %sp%s]" % (self.parent()._magma_init_(magma),
846
real_string, digit_precision_bound,
847
imag_string, digit_precision_bound)
848
849
def __nonzero__(self):
850
"""
851
Return ``True`` if ``self`` is not zero. This is an internal function;
852
use :meth:`is_zero()` instead.
853
854
EXAMPLES::
855
856
sage: z = 1 + CC(I)
857
sage: z.is_zero()
858
False
859
"""
860
return not (mpfr_zero_p(self.__re) and mpfr_zero_p(self.__im))
861
862
def prec(self):
863
"""
864
Return precision of this complex number.
865
866
EXAMPLES::
867
868
sage: i = ComplexField(2000).0
869
sage: i.prec()
870
2000
871
"""
872
return self._parent.prec()
873
874
def real(self):
875
"""
876
Return real part of ``self``.
877
878
EXAMPLES::
879
880
sage: i = ComplexField(100).0
881
sage: z = 2 + 3*i
882
sage: x = z.real(); x
883
2.0000000000000000000000000000
884
sage: x.parent()
885
Real Field with 100 bits of precision
886
sage: z.real_part()
887
2.0000000000000000000000000000
888
"""
889
cdef real_mpfr.RealNumber x
890
x = real_mpfr.RealNumber(self._parent._real_field(), None)
891
mpfr_set(x.value, self.__re, rnd)
892
return x
893
894
real_part = real
895
896
def imag(self):
897
"""
898
Return imaginary part of ``self``.
899
900
EXAMPLES::
901
902
sage: i = ComplexField(100).0
903
sage: z = 2 + 3*i
904
sage: x = z.imag(); x
905
3.0000000000000000000000000000
906
sage: x.parent()
907
Real Field with 100 bits of precision
908
sage: z.imag_part()
909
3.0000000000000000000000000000
910
"""
911
cdef real_mpfr.RealNumber x
912
x = real_mpfr.RealNumber(self._parent._real_field(), None)
913
mpfr_set(x.value, self.__im, rnd)
914
return x
915
916
imag_part = imag
917
918
def __neg__(self):
919
r"""
920
Method for computing the negative of ``self``.
921
922
.. MATH::
923
924
-(a + bi) = -a - bi
925
926
EXAMPLES::
927
928
sage: a = ComplexNumber(2,1)
929
sage: -a
930
-2.00000000000000 - 1.00000000000000*I
931
sage: a.__neg__()
932
-2.00000000000000 - 1.00000000000000*I
933
"""
934
cdef ComplexNumber x
935
x = self._new()
936
mpfr_neg(x.__re, self.__re, rnd)
937
mpfr_neg(x.__im, self.__im, rnd)
938
return x
939
940
def __pos__(self):
941
r"""
942
Method for computing the "positive" of ``self``.
943
944
EXAMPLES::
945
946
sage: a = ComplexNumber(2,1)
947
sage: +a
948
2.00000000000000 + 1.00000000000000*I
949
sage: a.__pos__()
950
2.00000000000000 + 1.00000000000000*I
951
"""
952
return self
953
954
def __abs__(self):
955
r"""
956
Method for computing the absolute value or modulus of ``self``
957
958
.. MATH::
959
960
`|a + bi| = sqrt(a^2 + b^2)`
961
962
EXAMPLES:
963
964
Note that the absolute value of a complex number with imaginary
965
component equal to zero is the absolute value of the real component.
966
967
::
968
969
sage: a = ComplexNumber(2,1)
970
sage: abs(a)
971
2.23606797749979
972
sage: a.__abs__()
973
2.23606797749979
974
sage: float(sqrt(2^2 + 1^1))
975
2.23606797749979
976
977
::
978
979
sage: b = ComplexNumber(42,0)
980
sage: abs(b)
981
42.0000000000000
982
sage: b.__abs__()
983
42.0000000000000
984
sage: b
985
42.0000000000000
986
"""
987
return self.abs_c()
988
989
def __invert__(self):
990
"""
991
Return the multiplicative inverse.
992
993
EXAMPLES::
994
995
sage: I = CC.0
996
sage: a = ~(5+I)
997
sage: a * (5+I)
998
1.00000000000000
999
"""
1000
cdef ComplexNumber x
1001
x = self._new()
1002
1003
cdef mpfr_t t0, t1
1004
mpfr_init2(t0, self._prec)
1005
mpfr_init2(t1, self._prec)
1006
1007
mpfr_mul(t0, self.__re, self.__re, rnd)
1008
mpfr_mul(t1, self.__im, self.__im, rnd)
1009
1010
mpfr_add(t0, t0, t1, rnd) # now t0 is the norm
1011
mpfr_div(x.__re, self.__re, t0, rnd) # x.__re = self.__re/norm
1012
1013
mpfr_neg(t1, self.__im, rnd)
1014
mpfr_div(x.__im, t1, t0, rnd) # x.__im = -self.__im/norm
1015
1016
mpfr_clear(t0)
1017
mpfr_clear(t1)
1018
1019
return x
1020
1021
def __int__(self):
1022
r"""
1023
Method for converting ``self`` to type ``int``.
1024
1025
Called by the ``int`` function. Note that calling this method returns
1026
an error since, in general, complex numbers cannot be coerced into
1027
integers.
1028
1029
EXAMPLES::
1030
1031
sage: a = ComplexNumber(2,1)
1032
sage: int(a)
1033
Traceback (most recent call last):
1034
...
1035
TypeError: can't convert complex to int; use int(abs(z))
1036
sage: a.__int__()
1037
Traceback (most recent call last):
1038
...
1039
TypeError: can't convert complex to int; use int(abs(z))
1040
"""
1041
raise TypeError, "can't convert complex to int; use int(abs(z))"
1042
1043
def __long__(self):
1044
r"""
1045
Method for converting ``self`` to type ``long``.
1046
1047
Called by the ``long`` function. Note that calling this method
1048
returns an error since, in general, complex numbers cannot be
1049
coerced into integers.
1050
1051
EXAMPLES::
1052
1053
sage: a = ComplexNumber(2,1)
1054
sage: long(a)
1055
Traceback (most recent call last):
1056
...
1057
TypeError: can't convert complex to long; use long(abs(z))
1058
sage: a.__long__()
1059
Traceback (most recent call last):
1060
...
1061
TypeError: can't convert complex to long; use long(abs(z))
1062
"""
1063
raise TypeError, "can't convert complex to long; use long(abs(z))"
1064
1065
def __float__(self):
1066
r"""
1067
Method for converting ``self`` to type ``float``.
1068
1069
Called by the ``float`` function. This conversion will throw an error
1070
if the number has a nonzero imaginary part.
1071
1072
EXAMPLES::
1073
1074
sage: a = ComplexNumber(1, 0)
1075
sage: float(a)
1076
1.0
1077
sage: a = ComplexNumber(2,1)
1078
sage: float(a)
1079
Traceback (most recent call last):
1080
...
1081
TypeError: Unable to convert 2.00000000000000 + 1.00000000000000*I to float; use abs() or real_part() as desired
1082
sage: a.__float__()
1083
Traceback (most recent call last):
1084
...
1085
TypeError: Unable to convert 2.00000000000000 + 1.00000000000000*I to float; use abs() or real_part() as desired
1086
sage: float(abs(ComplexNumber(1,1)))
1087
1.4142135623730951
1088
"""
1089
if mpfr_zero_p(self.__im):
1090
return mpfr_get_d(self.__re, rnd)
1091
else:
1092
raise TypeError, "Unable to convert %s to float; use abs() or real_part() as desired"%self
1093
1094
def __complex__(self):
1095
r"""
1096
Method for converting ``self`` to type ``complex``.
1097
1098
Called by the ``complex`` function.
1099
1100
EXAMPLES::
1101
1102
sage: a = ComplexNumber(2,1)
1103
sage: complex(a)
1104
(2+1j)
1105
sage: type(complex(a))
1106
<type 'complex'>
1107
sage: a.__complex__()
1108
(2+1j)
1109
"""
1110
return complex(mpfr_get_d(self.__re, rnd),
1111
mpfr_get_d(self.__im, rnd))
1112
# return complex(float(self.__re), float(self.__im))
1113
1114
def __richcmp__(left, right, int op):
1115
"""
1116
Rich comparision between ``left`` and ``right``.
1117
1118
EXAMPLES::
1119
1120
sage: cmp(CC(2, 1), CC(-1, 2))
1121
1
1122
sage: cmp(CC(2, 1), CC(2, 1))
1123
0
1124
"""
1125
return (<Element>left)._richcmp(right, op)
1126
1127
cdef int _cmp_c_impl(left, sage.structure.element.Element right) except -2:
1128
cdef int a, b
1129
a = mpfr_nan_p(left.__re)
1130
b = mpfr_nan_p((<ComplexNumber>right).__re)
1131
if a != b:
1132
return -1
1133
1134
cdef int i
1135
i = mpfr_cmp(left.__re, (<ComplexNumber>right).__re)
1136
if i < 0:
1137
return -1
1138
elif i > 0:
1139
return 1
1140
i = mpfr_cmp(left.__im, (<ComplexNumber>right).__im)
1141
if i < 0:
1142
return -1
1143
elif i > 0:
1144
return 1
1145
return 0
1146
1147
def multiplicative_order(self):
1148
"""
1149
Return the multiplicative order of this complex number, if known,
1150
or raise a ``NotImplementedError``.
1151
1152
EXAMPLES::
1153
1154
sage: C.<i> = ComplexField()
1155
sage: i.multiplicative_order()
1156
4
1157
sage: C(1).multiplicative_order()
1158
1
1159
sage: C(-1).multiplicative_order()
1160
2
1161
sage: C(i^2).multiplicative_order()
1162
2
1163
sage: C(-i).multiplicative_order()
1164
4
1165
sage: C(2).multiplicative_order()
1166
+Infinity
1167
sage: w = (1+sqrt(-3.0))/2; w
1168
0.500000000000000 + 0.866025403784439*I
1169
sage: abs(w)
1170
1.00000000000000
1171
sage: w.multiplicative_order()
1172
Traceback (most recent call last):
1173
...
1174
NotImplementedError: order of element not known
1175
"""
1176
if self == 1:
1177
return integer.Integer(1)
1178
elif self == -1:
1179
return integer.Integer(2)
1180
elif self == self._parent.gen():
1181
return integer.Integer(4)
1182
elif self == -self._parent.gen():
1183
return integer.Integer(4)
1184
elif not self._multiplicative_order is None:
1185
return integer.Integer(self._multiplicative_order)
1186
elif abs(abs(self) - 1) > 0.1: # clearly not a root of unity
1187
return infinity.infinity
1188
raise NotImplementedError, "order of element not known"
1189
1190
1191
########################################################################
1192
# Plotting
1193
########################################################################
1194
1195
def plot(self, **kargs):
1196
"""
1197
Plots this complex number as a point in the plane
1198
1199
The accepted options are the ones of :meth:`~sage.plot.point.point2d`.
1200
Type ``point2d.options`` to see all options.
1201
1202
.. NOTE::
1203
1204
Just wraps the sage.plot.point.point2d method
1205
1206
EXAMPLES:
1207
1208
You can either use the indirect::
1209
1210
sage: z = CC(0,1)
1211
sage: plot(z)
1212
1213
or the more direct::
1214
1215
sage: z = CC(0,1)
1216
sage: z.plot()
1217
"""
1218
return sage.plot.point.point2d((self.real(), self.imag()), **kargs)
1219
1220
########################################################################
1221
# Transcendental (and other) functions
1222
########################################################################
1223
1224
# Trig functions
1225
def arccos(self):
1226
"""
1227
Return the arccosine of ``self``.
1228
1229
EXAMPLES::
1230
1231
sage: (1+CC(I)).arccos()
1232
0.904556894302381 - 1.06127506190504*I
1233
"""
1234
return self._parent(self._pari_().acos())
1235
1236
def arccosh(self):
1237
"""
1238
Return the hyperbolic arccosine of ``self``.
1239
1240
EXAMPLES::
1241
1242
sage: (1+CC(I)).arccosh()
1243
1.06127506190504 + 0.904556894302381*I
1244
"""
1245
return self._parent(self._pari_().acosh())
1246
1247
def arcsin(self):
1248
"""
1249
Return the arcsine of ``self``.
1250
1251
EXAMPLES::
1252
1253
sage: (1+CC(I)).arcsin()
1254
0.666239432492515 + 1.06127506190504*I
1255
"""
1256
return self._parent(self._pari_().asin())
1257
1258
def arcsinh(self):
1259
"""
1260
Return the hyperbolic arcsine of ``self``.
1261
1262
EXAMPLES::
1263
1264
sage: (1+CC(I)).arcsinh()
1265
1.06127506190504 + 0.666239432492515*I
1266
"""
1267
return self._parent(self._pari_().asinh())
1268
1269
def arctan(self):
1270
"""
1271
Return the arctangent of ``self``.
1272
1273
EXAMPLES::
1274
1275
sage: (1+CC(I)).arctan()
1276
1.01722196789785 + 0.402359478108525*I
1277
"""
1278
return self._parent(self._pari_().atan())
1279
1280
def arctanh(self):
1281
"""
1282
Return the hyperbolic arctangent of ``self``.
1283
1284
EXAMPLES::
1285
1286
sage: (1+CC(I)).arctanh()
1287
0.402359478108525 + 1.01722196789785*I
1288
"""
1289
return self._parent(self._pari_().atanh())
1290
1291
def coth(self):
1292
"""
1293
Return the hyperbolic cotangent of ``self``.
1294
1295
EXAMPLES::
1296
1297
sage: ComplexField(100)(1,1).coth()
1298
0.86801414289592494863584920892 - 0.21762156185440268136513424361*I
1299
"""
1300
return ~(self.tanh())
1301
1302
def arccoth(self):
1303
"""
1304
Return the hyperbolic arccotangent of ``self``.
1305
1306
EXAMPLES::
1307
1308
sage: ComplexField(100)(1,1).arccoth()
1309
0.40235947810852509365018983331 - 0.55357435889704525150853273009*I
1310
"""
1311
return (~self).arctanh()
1312
1313
def csc(self):
1314
"""
1315
Return the cosecant of ``self``.
1316
1317
EXAMPLES::
1318
1319
sage: ComplexField(100)(1,1).csc()
1320
0.62151801717042842123490780586 - 0.30393100162842645033448560451*I
1321
"""
1322
return ~(self.sin())
1323
1324
def csch(self):
1325
"""
1326
Return the hyperbolic cosecant of ``self``.
1327
1328
EXAMPLES::
1329
1330
sage: ComplexField(100)(1,1).csch()
1331
0.30393100162842645033448560451 - 0.62151801717042842123490780586*I
1332
"""
1333
return ~(self.sinh())
1334
1335
def arccsch(self):
1336
"""
1337
Return the hyperbolic arccosecant of ``self``.
1338
1339
EXAMPLES::
1340
1341
sage: ComplexField(100)(1,1).arccsch()
1342
0.53063753095251782601650945811 - 0.45227844715119068206365839783*I
1343
"""
1344
return (~self).arcsinh()
1345
1346
def sec(self):
1347
"""
1348
Return the secant of ``self``.
1349
1350
EXAMPLES::
1351
1352
sage: ComplexField(100)(1,1).sec()
1353
0.49833703055518678521380589177 + 0.59108384172104504805039169297*I
1354
"""
1355
return ~(self.cos())
1356
1357
def sech(self):
1358
"""
1359
Return the hyperbolic secant of ``self``.
1360
1361
EXAMPLES::
1362
1363
sage: ComplexField(100)(1,1).sech()
1364
0.49833703055518678521380589177 - 0.59108384172104504805039169297*I
1365
"""
1366
return ~(self.cosh())
1367
1368
def arcsech(self):
1369
"""
1370
Return the hyperbolic arcsecant of ``self``.
1371
1372
EXAMPLES::
1373
1374
sage: ComplexField(100)(1,1).arcsech()
1375
0.53063753095251782601650945811 - 1.1185178796437059371676632938*I
1376
"""
1377
return (~self).arccosh()
1378
1379
def cotan(self):
1380
"""
1381
Return the cotangent of ``self``.
1382
1383
EXAMPLES::
1384
1385
sage: (1+CC(I)).cotan()
1386
0.217621561854403 - 0.868014142895925*I
1387
sage: i = ComplexField(200).0
1388
sage: (1+i).cotan()
1389
0.21762156185440268136513424360523807352075436916785404091068 - 0.86801414289592494863584920891627388827343874994609327121115*I
1390
sage: i = ComplexField(220).0
1391
sage: (1+i).cotan()
1392
0.21762156185440268136513424360523807352075436916785404091068124239 - 0.86801414289592494863584920891627388827343874994609327121115071646*I
1393
"""
1394
return ~(self.tan())
1395
1396
def cos(self):
1397
"""
1398
Return the cosine of ``self``.
1399
1400
EXAMPLES::
1401
1402
sage: (1+CC(I)).cos()
1403
0.833730025131149 - 0.988897705762865*I
1404
"""
1405
# write self = a + i*b, then
1406
# cos(self) = cosh(b)*cos(a) - i*sinh(b)*sin(a)
1407
cdef ComplexNumber z
1408
z = self._new()
1409
cdef mpfr_t ch, sh
1410
mpfr_init2(sh, self._prec)
1411
mpfr_sinh(sh, self.__im, rnd)
1412
mpfr_init2(ch, self._prec)
1413
mpfr_sqr(ch, sh, rnd)
1414
mpfr_add_ui(ch, ch, 1, rnd)
1415
mpfr_sqrt(ch, ch, rnd)
1416
mpfr_neg(sh, sh, rnd)
1417
mpfr_sin_cos(z.__im, z.__re, self.__re, rnd)
1418
mpfr_mul(z.__re, z.__re, ch, rnd)
1419
mpfr_mul(z.__im, z.__im, sh, rnd)
1420
mpfr_clear(sh)
1421
mpfr_clear(ch)
1422
return z
1423
1424
def cosh(self):
1425
"""
1426
Return the hyperbolic cosine of ``self``.
1427
1428
EXAMPLES::
1429
1430
sage: (1+CC(I)).cosh()
1431
0.833730025131149 + 0.988897705762865*I
1432
"""
1433
# write self = a + i*b, then
1434
# cosh(self) = cosh(a)*cos(b) + i*sinh(a)*sin(b)
1435
cdef ComplexNumber z
1436
z = self._new()
1437
cdef mpfr_t ch, sh
1438
mpfr_init2(sh, self._prec)
1439
mpfr_sinh(sh, self.__re, rnd)
1440
mpfr_init2(ch, self._prec)
1441
mpfr_sqr(ch, sh, rnd)
1442
mpfr_add_ui(ch, ch, 1, rnd)
1443
mpfr_sqrt(ch, ch, rnd)
1444
mpfr_sin_cos(z.__im, z.__re, self.__im, rnd)
1445
mpfr_mul(z.__re, z.__re, ch, rnd)
1446
mpfr_mul(z.__im, z.__im, sh, rnd)
1447
mpfr_clear(sh)
1448
mpfr_clear(ch)
1449
return z
1450
1451
1452
1453
def eta(self, omit_frac=False):
1454
r"""
1455
Return the value of the Dedekind `\eta` function on ``self``,
1456
intelligently computed using `\mathbb{SL}(2,\ZZ)`
1457
transformations.
1458
1459
The `\eta` function is
1460
1461
.. MATH::
1462
1463
\eta(z) = e^{\pi i z / 12} \prod_{n=1}^{\infty}(1-e^{2\pi inz})
1464
1465
INPUT:
1466
1467
- ``self`` -- element of the upper half plane (if not,
1468
raises a ``ValueError``).
1469
1470
- ``omit_frac`` -- (bool, default: ``False``), if ``True``,
1471
omit the `e^{\pi i z / 12}` factor.
1472
1473
OUTPUT: a complex number
1474
1475
ALGORITHM: Uses the PARI C library.
1476
1477
EXAMPLES:
1478
1479
First we compute `\eta(1+i)`::
1480
1481
sage: i = CC.0
1482
sage: z = 1+i; z.eta()
1483
0.742048775836565 + 0.198831370229911*I
1484
1485
We compute eta to low precision directly from the definition::
1486
1487
sage: z = 1 + i; z.eta()
1488
0.742048775836565 + 0.198831370229911*I
1489
sage: pi = CC(pi) # otherwise we will get a symbolic result.
1490
sage: exp(pi * i * z / 12) * prod([1-exp(2*pi*i*n*z) for n in range(1,10)])
1491
0.742048775836565 + 0.198831370229911*I
1492
1493
The optional argument allows us to omit the fractional part::
1494
1495
sage: z = 1 + i
1496
sage: z.eta(omit_frac=True)
1497
0.998129069925959 - 8.12769318...e-22*I
1498
sage: prod([1-exp(2*pi*i*n*z) for n in range(1,10)])
1499
0.998129069925958 + 4.59099857829247e-19*I
1500
1501
We illustrate what happens when `z` is not in the upper
1502
half plane::
1503
1504
sage: z = CC(1)
1505
sage: z.eta()
1506
Traceback (most recent call last):
1507
...
1508
ValueError: value must be in the upper half plane
1509
1510
You can also use functional notation::
1511
1512
sage: eta(1+CC(I))
1513
0.742048775836565 + 0.198831370229911*I
1514
"""
1515
try:
1516
return self._parent(self._pari_().eta(not omit_frac))
1517
except sage.libs.pari.all.PariError:
1518
raise ValueError, "value must be in the upper half plane"
1519
1520
1521
def sin(self):
1522
"""
1523
Return the sine of ``self``.
1524
1525
EXAMPLES::
1526
1527
sage: (1+CC(I)).sin()
1528
1.29845758141598 + 0.634963914784736*I
1529
"""
1530
# write self = a + i*b, then
1531
# sin(self) = cosh(b)*sin(a) + i*sinh(b)*cos(a)
1532
cdef ComplexNumber z
1533
z = self._new()
1534
cdef mpfr_t ch, sh
1535
mpfr_init2(sh, self._prec)
1536
mpfr_sinh(sh, self.__im, rnd)
1537
mpfr_init2(ch, self._prec)
1538
mpfr_sqr(ch, sh, rnd)
1539
mpfr_add_ui(ch, ch, 1, rnd)
1540
mpfr_sqrt(ch, ch, rnd)
1541
mpfr_sin_cos(z.__re, z.__im, self.__re, rnd)
1542
mpfr_mul(z.__re, z.__re, ch, rnd)
1543
mpfr_mul(z.__im, z.__im, sh, rnd)
1544
mpfr_clear(sh)
1545
mpfr_clear(ch)
1546
return z
1547
1548
def sinh(self):
1549
"""
1550
Return the hyperbolic sine of ``self``.
1551
1552
EXAMPLES::
1553
1554
sage: (1+CC(I)).sinh()
1555
0.634963914784736 + 1.29845758141598*I
1556
"""
1557
# write self = a + i*b, then
1558
# sinh(self) = sinh(a)*cos(b) + i*cosh(a)*sin(b)
1559
cdef ComplexNumber z
1560
z = self._new()
1561
cdef mpfr_t ch, sh
1562
mpfr_init2(sh, self._prec)
1563
mpfr_sinh(sh, self.__re, rnd)
1564
mpfr_init2(ch, self._prec)
1565
mpfr_sqr(ch, sh, rnd)
1566
mpfr_add_ui(ch, ch, 1, rnd)
1567
mpfr_sqrt(ch, ch, rnd)
1568
mpfr_sin_cos(z.__im, z.__re, self.__im, rnd)
1569
mpfr_mul(z.__re, z.__re, sh, rnd)
1570
mpfr_mul(z.__im, z.__im, ch, rnd)
1571
mpfr_clear(sh)
1572
mpfr_clear(ch)
1573
return z
1574
1575
def tan(self):
1576
"""
1577
Return the tangent of ``self``.
1578
1579
EXAMPLES::
1580
1581
sage: (1+CC(I)).tan()
1582
0.271752585319512 + 1.08392332733869*I
1583
"""
1584
# write self = a + i*b, then
1585
# tan(self) = [cos(a)*sin(a) + i*cosh(b)*sinh(b)]/[sinh^2(b)+cos^2(a)]
1586
cdef ComplexNumber z
1587
z = self._new()
1588
cdef mpfr_t ch, sh, c, s, a, b
1589
mpfr_init2(sh, self._prec)
1590
mpfr_sinh(sh, self.__im, rnd)
1591
mpfr_init2(ch, self._prec)
1592
mpfr_init2(a, self._prec)
1593
mpfr_sqr(a, sh, rnd)
1594
mpfr_add_ui(ch, a, 1, rnd)
1595
mpfr_sqrt(ch, ch, rnd)
1596
mpfr_init2(c, self._prec)
1597
mpfr_init2(s, self._prec)
1598
mpfr_sin_cos(s, c, self.__re, rnd)
1599
mpfr_init2(b, self._prec)
1600
mpfr_sqr(b, c, rnd)
1601
mpfr_add(a, a, b, rnd)
1602
mpfr_mul(z.__re, c, s, rnd)
1603
mpfr_div(z.__re, z.__re, a, rnd)
1604
mpfr_mul(z.__im, ch, sh, rnd)
1605
mpfr_div(z.__im, z.__im, a, rnd)
1606
mpfr_clear(sh)
1607
mpfr_clear(ch)
1608
mpfr_clear(c)
1609
mpfr_clear(s)
1610
mpfr_clear(b)
1611
mpfr_clear(a)
1612
return z
1613
1614
1615
def tanh(self):
1616
"""
1617
Return the hyperbolic tangent of ``self``.
1618
1619
EXAMPLES::
1620
1621
sage: (1+CC(I)).tanh()
1622
1.08392332733869 + 0.271752585319512*I
1623
"""
1624
# write self = a + i*b, then
1625
# tanh(self) = [cosh(a)*sinh(a) + i*cos(b)*sin(b)]/[sinh^2(a)+cos^2(b)]
1626
cdef ComplexNumber z
1627
z = self._new()
1628
cdef mpfr_t ch, sh, c, s, a, b
1629
mpfr_init2(sh, self._prec)
1630
mpfr_sinh(sh, self.__re, rnd)
1631
mpfr_init2(ch, self._prec)
1632
mpfr_init2(a, self._prec)
1633
mpfr_sqr(a, sh, rnd)
1634
mpfr_add_ui(ch, a, 1, rnd)
1635
mpfr_sqrt(ch, ch, rnd)
1636
mpfr_init2(c, self._prec)
1637
mpfr_init2(s, self._prec)
1638
mpfr_sin_cos(s, c, self.__im, rnd)
1639
mpfr_init2(b, self._prec)
1640
mpfr_sqr(b, c, rnd)
1641
mpfr_add(a, a, b, rnd)
1642
mpfr_mul(z.__im, c, s, rnd)
1643
mpfr_div(z.__im, z.__im, a, rnd)
1644
mpfr_mul(z.__re, ch, sh, rnd)
1645
mpfr_div(z.__re, z.__re, a, rnd)
1646
mpfr_clear(sh)
1647
mpfr_clear(ch)
1648
mpfr_clear(c)
1649
mpfr_clear(s)
1650
mpfr_clear(b)
1651
mpfr_clear(a)
1652
return z
1653
1654
# Other special functions
1655
def agm(self, right, algorithm="optimal"):
1656
"""
1657
Return the Arithmetic-Geometric Mean (AGM) of ``self`` and ``right``.
1658
1659
INPUT:
1660
1661
- ``right`` (complex) -- another complex number
1662
1663
- ``algorithm`` (string, default "optimal") -- the algorithm to use
1664
(see below).
1665
1666
OUTPUT:
1667
1668
(complex) A value of the AGM of ``self`` and ``right``. Note that
1669
this is a multi-valued function, and the algorithm used
1670
affects the value returned, as follows:
1671
1672
- "pari": Call the sgm function from the pari library.
1673
1674
- "optimal": Use the AGM sequence such that at each stage
1675
`(a,b)` is replaced by `(a_1,b_1)=((a+b)/2,\pm\sqrt{ab})`
1676
where the sign is chosen so that `|a_1-b_1|\le|a_1+b_1|`, or
1677
equivalently `\Re(b_1/a_1)\ge 0`. The resulting limit is
1678
maximal among all possible values.
1679
1680
- "principal": Use the AGM sequence such that at each stage
1681
`(a,b)` is replaced by `(a_1,b_1)=((a+b)/2,\pm\sqrt{ab})`
1682
where the sign is chosen so that `\Re(b_1)\ge 0` (the
1683
so-called principal branch of the square root).
1684
1685
The values `AGM(a,0)`, `AGM(0,a)`, and `AGM(a,-a)` are all taken to be 0.
1686
1687
EXAMPLES::
1688
1689
sage: a = CC(1,1)
1690
sage: b = CC(2,-1)
1691
sage: a.agm(b)
1692
1.62780548487271 + 0.136827548397369*I
1693
sage: a.agm(b, algorithm="optimal")
1694
1.62780548487271 + 0.136827548397369*I
1695
sage: a.agm(b, algorithm="principal")
1696
1.62780548487271 + 0.136827548397369*I
1697
sage: a.agm(b, algorithm="pari")
1698
1.62780548487271 + 0.136827548397369*I
1699
1700
An example to show that the returned value depends on the algorithm
1701
parameter::
1702
1703
sage: a = CC(-0.95,-0.65)
1704
sage: b = CC(0.683,0.747)
1705
sage: a.agm(b, algorithm="optimal")
1706
-0.371591652351761 + 0.319894660206830*I
1707
sage: a.agm(b, algorithm="principal")
1708
0.338175462986180 - 0.0135326969565405*I
1709
sage: a.agm(b, algorithm="pari")
1710
0.0806891850759812 + 0.239036532685557*I
1711
sage: a.agm(b, algorithm="optimal").abs()
1712
0.490319232466314
1713
sage: a.agm(b, algorithm="principal").abs()
1714
0.338446122230459
1715
sage: a.agm(b, algorithm="pari").abs()
1716
0.252287947683910
1717
1718
TESTS:
1719
1720
An example which came up in testing::
1721
1722
sage: I = CC(I)
1723
sage: a = 0.501648970493109 + 1.11877240294744*I
1724
sage: b = 1.05946309435930 + 1.05946309435930*I
1725
sage: a.agm(b)
1726
0.774901870587681 + 1.10254945079875*I
1727
1728
sage: a = CC(-0.32599972608379413, 0.60395514542928641)
1729
sage: b = CC( 0.6062314525690593, 0.1425693337776659)
1730
sage: a.agm(b)
1731
0.199246281325876 + 0.478401702759654*I
1732
sage: a.agm(-a)
1733
0.000000000000000
1734
sage: a.agm(0)
1735
0.000000000000000
1736
sage: CC(0).agm(a)
1737
0.000000000000000
1738
1739
Consistency::
1740
1741
sage: a = 1 + 0.5*I
1742
sage: b = 2 - 0.25*I
1743
sage: a.agm(b) - ComplexField(100)(a).agm(b)
1744
0.000000000000000
1745
sage: ComplexField(200)(a).agm(b) - ComplexField(500)(a).agm(b)
1746
0.00000000000000000000000000000000000000000000000000000000000
1747
sage: ComplexField(500)(a).agm(b) - ComplexField(1000)(a).agm(b)
1748
0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
1749
"""
1750
if algorithm=="pari":
1751
t = self._parent(right)._pari_()
1752
return self._parent(self._pari_().agm(t))
1753
1754
cdef ComplexNumber a, b, a1, b1, d, e, res
1755
cdef mp_exp_t rel_prec
1756
cdef bint optimal = algorithm == "optimal"
1757
1758
if optimal or algorithm == "principal":
1759
1760
if not isinstance(right, ComplexNumber) or (<ComplexNumber>right)._parent is not self._parent:
1761
right = self._parent(right)
1762
1763
res = self._new()
1764
1765
if mpfr_zero_p(self.__re) and mpfr_zero_p(self.__im):
1766
return self
1767
elif mpfr_zero_p((<ComplexNumber>right).__re) and mpfr_zero_p((<ComplexNumber>right).__im):
1768
return right
1769
elif (mpfr_cmpabs(self.__re, (<ComplexNumber>right).__re) == 0 and
1770
mpfr_cmpabs(self.__im, (<ComplexNumber>right).__im) == 0 and
1771
mpfr_cmp(self.__re, (<ComplexNumber>right).__re) != 0 and
1772
mpfr_cmp(self.__im, (<ComplexNumber>right).__im) != 0):
1773
# self = -right
1774
mpfr_set_ui(res.__re, 0, rnd)
1775
mpfr_set_ui(res.__im, 0, rnd)
1776
return res
1777
1778
# Do the computations to a bit higher precicion so rounding error
1779
# won't obscure the termination condition.
1780
a = ComplexNumber(self._parent.to_prec(self._prec+5), None)
1781
b = a._new()
1782
a1 = a._new()
1783
b1 = a._new()
1784
1785
d = a._new()
1786
if optimal:
1787
e = a._new()
1788
1789
# Make copies so we don't mutate self or right.
1790
mpfr_set(a.__re, self.__re, rnd)
1791
mpfr_set(a.__im, self.__im, rnd)
1792
mpfr_set(b.__re, (<ComplexNumber>right).__re, rnd)
1793
mpfr_set(b.__im, (<ComplexNumber>right).__im, rnd)
1794
1795
if optimal:
1796
mpfr_add(e.__re, a.__re, b.__re, rnd)
1797
mpfr_add(e.__im, a.__im, b.__im, rnd)
1798
1799
while True:
1800
1801
# a1 = (a+b)/2
1802
if optimal:
1803
mpfr_swap(a1.__re, e.__re)
1804
mpfr_swap(a1.__im, e.__im)
1805
else:
1806
mpfr_add(a1.__re, a.__re, b.__re, rnd)
1807
mpfr_add(a1.__im, a.__im, b.__im, rnd)
1808
mpfr_mul_2si(a1.__re, a1.__re, -1, rnd)
1809
mpfr_mul_2si(a1.__im, a1.__im, -1, rnd)
1810
1811
# b1 = sqrt(a*b)
1812
mpfr_mul(d.__re, a.__re, b.__re, rnd)
1813
mpfr_mul(d.__im, a.__im, b.__im, rnd)
1814
mpfr_sub(b1.__re, d.__re, d.__im, rnd)
1815
mpfr_mul(d.__re, a.__re, b.__im, rnd)
1816
mpfr_mul(d.__im, a.__im, b.__re, rnd)
1817
mpfr_add(b1.__im, d.__re, d.__im, rnd)
1818
b1 = b1.sqrt() # this would be a *lot* of code duplication
1819
1820
# d = a1 - b1
1821
mpfr_sub(d.__re, a1.__re, b1.__re, rnd)
1822
mpfr_sub(d.__im, a1.__im, b1.__im, rnd)
1823
if mpfr_zero_p(d.__re) and mpfr_zero_p(d.__im):
1824
mpfr_set(res.__re, a1.__re, rnd)
1825
mpfr_set(res.__im, a1.__im, rnd)
1826
return res
1827
1828
if optimal:
1829
# e = a1+b1
1830
mpfr_add(e.__re, a1.__re, b1.__re, rnd)
1831
mpfr_add(e.__im, a1.__im, b1.__im, rnd)
1832
if mpfr_zero_p(e.__re) and mpfr_zero_p(e.__im):
1833
mpfr_set(res.__re, a1.__re, rnd)
1834
mpfr_set(res.__im, a1.__im, rnd)
1835
return res
1836
1837
# |e| < |d|
1838
if cmp_abs(e, d) < 0:
1839
mpfr_swap(d.__re, e.__re)
1840
mpfr_swap(d.__im, e.__im)
1841
mpfr_neg(b1.__re, b1.__re, rnd)
1842
mpfr_neg(b1.__im, b1.__im, rnd)
1843
1844
rel_prec = min_exp_t(max_exp(a1), max_exp(b1)) - max_exp(d)
1845
if rel_prec > self._prec:
1846
mpfr_set(res.__re, a1.__re, rnd)
1847
mpfr_set(res.__im, a1.__im, rnd)
1848
return res
1849
1850
# a, b = a1, b1
1851
mpfr_swap(a.__re, a1.__re)
1852
mpfr_swap(a.__im, a1.__im)
1853
mpfr_swap(b.__re, b1.__re)
1854
mpfr_swap(b.__im, b1.__im)
1855
1856
raise ValueError, "agm algorithm must be one of 'pari', 'optimal', 'principal'"
1857
1858
def argument(self):
1859
r"""
1860
The argument (angle) of the complex number, normalized so that
1861
`-\pi < \theta \leq \pi`.
1862
1863
EXAMPLES::
1864
1865
sage: i = CC.0
1866
sage: (i^2).argument()
1867
3.14159265358979
1868
sage: (1+i).argument()
1869
0.785398163397448
1870
sage: i.argument()
1871
1.57079632679490
1872
sage: (-i).argument()
1873
-1.57079632679490
1874
sage: (RR('-0.001') - i).argument()
1875
-1.57179632646156
1876
"""
1877
cdef real_mpfr.RealNumber x
1878
x = real_mpfr.RealNumber(self._parent._real_field(), None)
1879
mpfr_atan2(x.value, self.__im, self.__re, rnd)
1880
return x
1881
1882
1883
def arg(self):
1884
"""
1885
See :meth:`argument()`.
1886
1887
EXAMPLES::
1888
1889
sage: i = CC.0
1890
sage: (i^2).arg()
1891
3.14159265358979
1892
"""
1893
return self.argument()
1894
1895
def conjugate(self):
1896
"""
1897
Return the complex conjugate of this complex number.
1898
1899
EXAMPLES::
1900
1901
sage: i = CC.0
1902
sage: (1+i).conjugate()
1903
1.00000000000000 - 1.00000000000000*I
1904
"""
1905
cdef ComplexNumber x
1906
x = self._new()
1907
1908
cdef mpfr_t i
1909
mpfr_init2(i, self._prec)
1910
mpfr_neg(i, self.__im, rnd)
1911
mpfr_set(x.__re, self.__re, rnd)
1912
mpfr_set(x.__im, i, rnd)
1913
mpfr_clear(i)
1914
return x
1915
1916
def dilog(self):
1917
r"""
1918
Returns the complex dilogarithm of ``self``.
1919
1920
The complex dilogarithm, or Spence's function, is defined by
1921
1922
.. MATH::
1923
1924
Li_2(z) = - \int_0^z \frac{\log|1-\zeta|}{\zeta} d(\zeta)
1925
= \sum_{k=1}^\infty \frac{z^k}{k}
1926
1927
Note that the series definition can only be used for `|z| < 1`.
1928
1929
EXAMPLES::
1930
1931
sage: a = ComplexNumber(1,0)
1932
sage: a.dilog()
1933
1.64493406684823
1934
sage: float(pi^2/6)
1935
1.6449340668482262
1936
1937
::
1938
1939
sage: b = ComplexNumber(0,1)
1940
sage: b.dilog()
1941
-0.205616758356028 + 0.915965594177219*I
1942
1943
::
1944
1945
sage: c = ComplexNumber(0,0)
1946
sage: c.dilog()
1947
0.000000000000000
1948
"""
1949
return self._parent(self._pari_().dilog())
1950
1951
def exp(ComplexNumber self):
1952
r"""
1953
Compute `e^z` or `\exp(z)`.
1954
1955
EXAMPLES::
1956
1957
sage: i = ComplexField(300).0
1958
sage: z = 1 + i
1959
sage: z.exp()
1960
1.46869393991588515713896759732660426132695673662900872279767567631093696585951213872272450 + 2.28735528717884239120817190670050180895558625666835568093865811410364716018934540926734485*I
1961
"""
1962
# write self = a + i*b, then
1963
# exp(self) = exp(a)*(cos(b) + i*sin(b))
1964
cdef ComplexNumber z
1965
z = self._new()
1966
cdef mpfr_t r
1967
mpfr_init2(r, self._prec)
1968
mpfr_exp(r, self.__re, rnd)
1969
mpfr_sin_cos(z.__im, z.__re, self.__im, rnd)
1970
mpfr_mul(z.__re, z.__re, r, rnd)
1971
mpfr_mul(z.__im, z.__im, r, rnd)
1972
mpfr_clear(r)
1973
return z
1974
1975
def gamma(self):
1976
"""
1977
Return the Gamma function evaluated at this complex number.
1978
1979
EXAMPLES::
1980
1981
sage: i = ComplexField(30).0
1982
sage: (1+i).gamma()
1983
0.49801567 - 0.15494983*I
1984
1985
TESTS::
1986
1987
sage: CC(0).gamma()
1988
Infinity
1989
1990
::
1991
1992
sage: CC(-1).gamma()
1993
Infinity
1994
"""
1995
try:
1996
return self._parent(self._pari_().gamma())
1997
except sage.libs.pari.all.PariError:
1998
from sage.rings.infinity import UnsignedInfinityRing
1999
return UnsignedInfinityRing.gen()
2000
2001
def gamma_inc(self, t):
2002
"""
2003
Return the incomplete Gamma function evaluated at this complex
2004
number.
2005
2006
EXAMPLES::
2007
2008
sage: C, i = ComplexField(30).objgen()
2009
sage: (1+i).gamma_inc(2 + 3*i)
2010
0.0020969149 - 0.059981914*I
2011
sage: (1+i).gamma_inc(5)
2012
-0.0013781309 + 0.0065198200*I
2013
sage: C(2).gamma_inc(1 + i)
2014
0.70709210 - 0.42035364*I
2015
sage: CC(2).gamma_inc(5)
2016
0.0404276819945128
2017
"""
2018
return self._parent(self._pari_().incgam(t))
2019
2020
def log(self,base=None):
2021
r"""
2022
Complex logarithm of `z` with branch chosen as follows: Write
2023
`z = \rho e^{i \theta}` with `-\pi < \theta <= pi`. Then
2024
`\mathrm{log}(z) = \mathrm{log}(\rho) + i \theta`.
2025
2026
.. WARNING::
2027
2028
Currently the real log is computed using floats, so there
2029
is potential precision loss.
2030
2031
EXAMPLES::
2032
2033
sage: a = ComplexNumber(2,1)
2034
sage: a.log()
2035
0.804718956217050 + 0.463647609000806*I
2036
sage: log(a.abs())
2037
0.804718956217050
2038
sage: a.argument()
2039
0.463647609000806
2040
2041
::
2042
2043
sage: b = ComplexNumber(float(exp(42)),0)
2044
sage: b.log()
2045
41.99999999999971
2046
2047
::
2048
2049
sage: c = ComplexNumber(-1,0)
2050
sage: c.log()
2051
3.14159265358979*I
2052
2053
The option of a base is included for compatibility with other logs::
2054
2055
sage: c = ComplexNumber(-1,0)
2056
sage: c.log(2)
2057
4.53236014182719*I
2058
2059
If either component (real or imaginary) of the complex number
2060
is NaN (not a number), log will return the complex NaN::
2061
2062
sage: c = ComplexNumber(NaN,2)
2063
sage: c.log()
2064
NaN - NaN*I
2065
2066
"""
2067
if mpfr_nan_p(self.__re):
2068
return ComplexNumber(self._parent,self.real(),self.real())
2069
if mpfr_nan_p(self.__im):
2070
return ComplexNumber(self._parent,self.imag(),self.imag())
2071
theta = self.argument()
2072
rho = abs(self)
2073
if base is None:
2074
return ComplexNumber(self._parent, rho.log(), theta)
2075
else:
2076
from real_mpfr import RealField
2077
return ComplexNumber(self._parent, rho.log()/RealNumber(RealField(self.prec()),base).log(), theta/RealNumber(RealField(self.prec()),base).log())
2078
2079
def additive_order(self):
2080
"""
2081
Return the additive order of ``self``.
2082
2083
EXAMPLES::
2084
2085
sage: CC(0).additive_order()
2086
1
2087
sage: CC.gen().additive_order()
2088
+Infinity
2089
"""
2090
if self == 0:
2091
return 1
2092
else:
2093
return infinity.infinity
2094
2095
def sqrt(self, all=False):
2096
"""
2097
The square root function, taking the branch cut to be the negative
2098
real axis.
2099
2100
INPUT:
2101
2102
- ``all`` - bool (default: ``False``); if ``True``, return a
2103
list of all square roots.
2104
2105
EXAMPLES::
2106
2107
sage: C.<i> = ComplexField(30)
2108
sage: i.sqrt()
2109
0.70710678 + 0.70710678*I
2110
sage: (1+i).sqrt()
2111
1.0986841 + 0.45508986*I
2112
sage: (C(-1)).sqrt()
2113
1.0000000*I
2114
sage: (1 + 1e-100*i).sqrt()^2
2115
1.0000000 + 1.0000000e-100*I
2116
sage: i = ComplexField(200).0
2117
sage: i.sqrt()
2118
0.70710678118654752440084436210484903928483593768847403658834 + 0.70710678118654752440084436210484903928483593768847403658834*I
2119
"""
2120
cdef ComplexNumber z = self._new()
2121
if mpfr_zero_p(self.__im):
2122
if mpfr_sgn(self.__re) >= 0:
2123
mpfr_set_ui(z.__im, 0, rnd)
2124
mpfr_sqrt(z.__re, self.__re, rnd)
2125
else:
2126
mpfr_set_ui(z.__re, 0, rnd)
2127
mpfr_neg(z.__im, self.__re, rnd)
2128
mpfr_sqrt(z.__im, z.__im, rnd)
2129
if all:
2130
return [z, -z] if z else [z]
2131
else:
2132
return z
2133
# self = x + yi = (a+bi)^2
2134
# expand, substitute, solve
2135
# a^2 = (x + sqrt(x^2+y^2))/2
2136
cdef bint avoid_branch = mpfr_sgn(self.__re) < 0 and mpfr_cmpabs(self.__im, self.__re) < 0
2137
cdef mpfr_t a2
2138
mpfr_init2(a2, self._prec)
2139
mpfr_hypot(a2, self.__re, self.__im, rnd)
2140
if avoid_branch:
2141
# x + sqrt(x^2+y^2) numerically unstable for x near negative real axis
2142
# so we compute sqrt of (-z) and shift by i at the end
2143
mpfr_sub(a2, a2, self.__re, rnd)
2144
else:
2145
mpfr_add(a2, a2, self.__re, rnd)
2146
mpfr_mul_2si(a2, a2, -1, rnd)
2147
# a = sqrt(a2)
2148
mpfr_sqrt(z.__re, a2, rnd)
2149
# b = y/(2a)
2150
mpfr_div(z.__im, self.__im, z.__re, rnd)
2151
mpfr_mul_2si(z.__im, z.__im, -1, rnd)
2152
mpfr_clear(a2)
2153
if avoid_branch:
2154
mpfr_swap(z.__re, z.__im)
2155
# Note that y (hence b) was never negated, so we have z=i*sqrt(self).
2156
# if we were below the branch cut, we want the other branch
2157
if mpfr_sgn(self.__im) < 0:
2158
mpfr_neg(z.__re, z.__re, rnd)
2159
mpfr_neg(z.__im, z.__im, rnd)
2160
if all:
2161
return [z, -z]
2162
else:
2163
return z
2164
2165
def nth_root(self, n, all=False):
2166
"""
2167
The `n`-th root function.
2168
2169
INPUT:
2170
2171
- ``all`` - bool (default: ``False``); if ``True``, return a
2172
list of all `n`-th roots.
2173
2174
EXAMPLES::
2175
2176
sage: a = CC(27)
2177
sage: a.nth_root(3)
2178
3.00000000000000
2179
sage: a.nth_root(3, all=True)
2180
[3.00000000000000, -1.50000000000000 + 2.59807621135332*I, -1.50000000000000 - 2.59807621135332*I]
2181
sage: a = ComplexField(20)(2,1)
2182
sage: [r^7 for r in a.nth_root(7, all=True)]
2183
[2.0000 + 1.0000*I, 2.0000 + 1.0000*I, 2.0000 + 1.0000*I, 2.0000 + 1.0000*I, 2.0000 + 1.0000*I, 2.0000 + 1.0001*I, 2.0000 + 1.0001*I]
2184
"""
2185
if self.is_zero():
2186
return [self] if all else self
2187
2188
cdef ComplexNumber z
2189
z = self._new()
2190
2191
cdef real_mpfr.RealNumber arg, rho
2192
cdef mpfr_t r
2193
rho = abs(self)
2194
arg = self.argument() / n
2195
mpfr_init2(r, self._prec)
2196
mpfr_root(r, rho.value, n, rnd)
2197
2198
mpfr_sin_cos(z.__im, z.__re, arg.value, rnd)
2199
mpfr_mul(z.__re, z.__re, r, rnd)
2200
mpfr_mul(z.__im, z.__im, r, rnd)
2201
2202
if not all:
2203
mpfr_clear(r)
2204
return z
2205
2206
R = self._parent._real_field()
2207
cdef real_mpfr.RealNumber theta
2208
theta = R.pi()*2/n
2209
zlist = [z]
2210
for k in range(1, n):
2211
z = self._new()
2212
arg += theta
2213
mpfr_sin_cos(z.__im, z.__re, arg.value, rnd)
2214
mpfr_mul(z.__re, z.__re, r, rnd)
2215
mpfr_mul(z.__im, z.__im, r, rnd)
2216
zlist.append(z)
2217
2218
mpfr_clear(r)
2219
return zlist
2220
2221
2222
def is_square(self):
2223
r"""
2224
This function always returns true as `\CC` is algebraically closed.
2225
2226
EXAMPLES::
2227
2228
sage: a = ComplexNumber(2,1)
2229
sage: a.is_square()
2230
True
2231
2232
`\CC` is algebraically closed, hence every element
2233
is a square::
2234
2235
sage: b = ComplexNumber(5)
2236
sage: b.is_square()
2237
True
2238
"""
2239
return True
2240
2241
def is_real(self):
2242
"""
2243
Return ``True`` if ``self`` is real, i.e. has imaginary part zero.
2244
2245
EXAMPLES::
2246
2247
sage: CC(1.23).is_real()
2248
True
2249
sage: CC(1+i).is_real()
2250
False
2251
"""
2252
return (mpfr_zero_p(self.__im) != 0)
2253
2254
def is_imaginary(self):
2255
"""
2256
Return ``True`` if ``self`` is imaginary, i.e. has real part zero.
2257
2258
EXAMPLES::
2259
2260
sage: CC(1.23*i).is_imaginary()
2261
True
2262
sage: CC(1+i).is_imaginary()
2263
False
2264
"""
2265
return (mpfr_zero_p(self.__re) != 0)
2266
2267
def zeta(self):
2268
"""
2269
Return the Riemann zeta function evaluated at this complex number.
2270
2271
EXAMPLES::
2272
2273
sage: i = ComplexField(30).gen()
2274
sage: z = 1 + i
2275
sage: z.zeta()
2276
0.58215806 - 0.92684856*I
2277
sage: zeta(z)
2278
0.58215806 - 0.92684856*I
2279
2280
sage: CC(1).zeta()
2281
Infinity
2282
"""
2283
if mpfr_zero_p(self.__im) and mpfr_cmp_ui(self.__re, 1) == 0:
2284
import infinity
2285
return infinity.unsigned_infinity
2286
return self._parent(self._pari_().zeta())
2287
2288
def algdep(self, n, **kwds):
2289
"""
2290
Returns a polynomial of degree at most `n` which is
2291
approximately satisfied by this complex number. Note that the
2292
returned polynomial need not be irreducible, and indeed usually
2293
won't be if `z` is a good approximation to an algebraic
2294
number of degree less than `n`.
2295
2296
ALGORITHM: Uses the PARI C-library algdep command.
2297
2298
INPUT: Type algdep? at the top level prompt. All additional
2299
parameters are passed onto the top-level algdep command.
2300
2301
EXAMPLE::
2302
2303
sage: C = ComplexField()
2304
sage: z = (1/2)*(1 + sqrt(3.0) *C.0); z
2305
0.500000000000000 + 0.866025403784439*I
2306
sage: p = z.algdep(5); p
2307
x^3 + 1
2308
sage: p.factor()
2309
(x + 1) * (x^2 - x + 1)
2310
sage: z^2 - z + 1
2311
1.11022302462516e-16
2312
"""
2313
import sage.rings.arith
2314
return sage.rings.arith.algdep(self,n, **kwds)
2315
2316
def algebraic_dependancy( self, n ):
2317
"""
2318
Returns a polynomial of degree at most `n` which is
2319
approximately satisfied by this complex number. Note that the
2320
returned polynomial need not be irreducible, and indeed usually
2321
won't be if `z` is a good approximation to an algebraic
2322
number of degree less than `n`.
2323
2324
ALGORITHM: Uses the PARI C-library algdep command.
2325
2326
INPUT: Type algdep? at the top level prompt. All additional
2327
parameters are passed onto the top-level algdep command.
2328
2329
EXAMPLE::
2330
2331
sage: C = ComplexField()
2332
sage: z = (1/2)*(1 + sqrt(3.0) *C.0); z
2333
0.500000000000000 + 0.866025403784439*I
2334
sage: p = z.algebraic_dependancy(5); p
2335
x^3 + 1
2336
sage: p.factor()
2337
(x + 1) * (x^2 - x + 1)
2338
sage: z^2 - z + 1
2339
1.11022302462516e-16
2340
"""
2341
return self.algdep( n )
2342
2343
def make_ComplexNumber0( fld, mult_order, re, im ):
2344
"""
2345
Create a complex number for pickling.
2346
2347
EXAMPLES::
2348
2349
sage: a = CC(1 + I)
2350
sage: loads(dumps(a)) == a # indirect doctest
2351
True
2352
"""
2353
x = ComplexNumber( fld, re, im )
2354
x._set_multiplicative_order( mult_order )
2355
return x
2356
2357
2358
2359
def create_ComplexNumber(s_real, s_imag=None, int pad=0, min_prec=53):
2360
r"""
2361
Return the complex number defined by the strings ``s_real`` and
2362
``s_imag`` as an element of ``ComplexField(prec=n)``,
2363
where `n` potentially has slightly more (controlled by pad) bits than
2364
given by `s`.
2365
2366
INPUT:
2367
2368
- ``s_real`` -- a string that defines a real number
2369
(or something whose string representation defines a number)
2370
2371
- ``s_imag`` -- a string that defines a real number
2372
(or something whose string representation defines a number)
2373
2374
- ``pad`` -- an integer at least 0.
2375
2376
- ``min_prec`` -- number will have at least this many bits of precision,
2377
no matter what.
2378
2379
EXAMPLES::
2380
2381
sage: ComplexNumber('2.3')
2382
2.30000000000000
2383
sage: ComplexNumber('2.3','1.1')
2384
2.30000000000000 + 1.10000000000000*I
2385
sage: ComplexNumber(10)
2386
10.0000000000000
2387
sage: ComplexNumber(10,10)
2388
10.0000000000000 + 10.0000000000000*I
2389
sage: ComplexNumber(1.000000000000000000000000000,2)
2390
1.00000000000000000000000000 + 2.00000000000000000000000000*I
2391
sage: ComplexNumber(1,2.000000000000000000000)
2392
1.00000000000000000000 + 2.00000000000000000000*I
2393
2394
::
2395
2396
sage: sage.rings.complex_number.create_ComplexNumber(s_real=2,s_imag=1)
2397
2.00000000000000 + 1.00000000000000*I
2398
2399
TESTS:
2400
2401
Make sure we've rounded up ``log(10,2)`` enough to guarantee
2402
sufficient precision (:trac:`10164`)::
2403
2404
sage: s = "1." + "0"*10**6 + "1"
2405
sage: sage.rings.complex_number.create_ComplexNumber(s,0).real()-1 == 0
2406
False
2407
sage: sage.rings.complex_number.create_ComplexNumber(0,s).imag()-1 == 0
2408
False
2409
2410
"""
2411
if s_imag is None:
2412
s_imag = 0
2413
2414
if not isinstance(s_real, str):
2415
s_real = str(s_real).strip()
2416
if not isinstance(s_imag, str):
2417
s_imag = str(s_imag).strip()
2418
#if base == 10:
2419
bits = max(int(LOG_TEN_TWO_PLUS_EPSILON*len(s_real)),
2420
int(LOG_TEN_TWO_PLUS_EPSILON*len(s_imag)))
2421
#else:
2422
# bits = max(int(math.log(base,2)*len(s_imag)),int(math.log(base,2)*len(s_imag)))
2423
2424
C = complex_field.ComplexField(prec=max(bits+pad, min_prec))
2425
2426
return ComplexNumber(C, s_real, s_imag)
2427
2428
2429
cdef class RRtoCC(Map):
2430
2431
cdef ComplexNumber _zero
2432
2433
def __init__(self, RR, CC):
2434
"""
2435
EXAMPLES::
2436
2437
sage: from sage.rings.complex_number import RRtoCC
2438
sage: RRtoCC(RR, CC)
2439
Natural map:
2440
From: Real Field with 53 bits of precision
2441
To: Complex Field with 53 bits of precision
2442
"""
2443
Map.__init__(self, RR, CC)
2444
self._zero = ComplexNumber(CC, 0)
2445
self._repr_type_str = "Natural"
2446
2447
cpdef Element _call_(self, x):
2448
"""
2449
EXAMPLES::
2450
2451
sage: from sage.rings.complex_number import RRtoCC
2452
sage: f = RRtoCC(RealField(100), ComplexField(10)) # indirect doctest
2453
sage: f(1/3)
2454
0.33
2455
"""
2456
cdef ComplexNumber z = self._zero._new()
2457
mpfr_set(z.__re, (<RealNumber>x).value, rnd)
2458
mpfr_set_ui(z.__im, 0, rnd)
2459
return z
2460
2461
2462
cdef class CCtoCDF(Map):
2463
2464
cpdef Element _call_(self, x):
2465
"""
2466
EXAMPLES::
2467
2468
sage: from sage.rings.complex_number import CCtoCDF
2469
sage: f = CCtoCDF(CC, CDF) # indirect doctest
2470
sage: f(CC.0)
2471
1.0*I
2472
sage: f(exp(pi*CC.0/4))
2473
0.707106781187 + 0.707106781187*I
2474
"""
2475
cdef ComplexDoubleElement z = <ComplexDoubleElement>PY_NEW(ComplexDoubleElement)
2476
z._complex.dat[0] = mpfr_get_d((<ComplexNumber>x).__re, GMP_RNDN)
2477
z._complex.dat[1] = mpfr_get_d((<ComplexNumber>x).__im, GMP_RNDN)
2478
return z
2479
2480
2481
cdef inline mp_exp_t min_exp_t(mp_exp_t a, mp_exp_t b):
2482
return a if a < b else b
2483
2484
cdef inline mp_exp_t max_exp_t(mp_exp_t a, mp_exp_t b):
2485
return a if a > b else b
2486
2487
cdef inline mp_exp_t max_exp(ComplexNumber z):
2488
"""
2489
Quickly return the maximum exponent of the real and complex parts of z,
2490
which is useful for estimating its magnitude.
2491
"""
2492
if mpfr_zero_p(z.__im):
2493
return mpfr_get_exp(z.__re)
2494
elif mpfr_zero_p(z.__re):
2495
return mpfr_get_exp(z.__im)
2496
return max_exp_t(mpfr_get_exp(z.__re), mpfr_get_exp(z.__im))
2497
2498
cpdef int cmp_abs(ComplexNumber a, ComplexNumber b):
2499
"""
2500
Returns -1, 0, or 1 according to whether `|a|` is less than, equal to, or
2501
greater than `|b|`.
2502
2503
Optimized for non-close numbers, where the ordering can be determined by
2504
examining exponents.
2505
2506
EXAMPLES::
2507
2508
sage: from sage.rings.complex_number import cmp_abs
2509
sage: cmp_abs(CC(5), CC(1))
2510
1
2511
sage: cmp_abs(CC(5), CC(4))
2512
1
2513
sage: cmp_abs(CC(5), CC(5))
2514
0
2515
sage: cmp_abs(CC(5), CC(6))
2516
-1
2517
sage: cmp_abs(CC(5), CC(100))
2518
-1
2519
sage: cmp_abs(CC(-100), CC(1))
2520
1
2521
sage: cmp_abs(CC(-100), CC(100))
2522
0
2523
sage: cmp_abs(CC(-100), CC(1000))
2524
-1
2525
sage: cmp_abs(CC(1,1), CC(1))
2526
1
2527
sage: cmp_abs(CC(1,1), CC(2))
2528
-1
2529
sage: cmp_abs(CC(1,1), CC(1,0.99999))
2530
1
2531
sage: cmp_abs(CC(1,1), CC(1,-1))
2532
0
2533
sage: cmp_abs(CC(0), CC(1))
2534
-1
2535
sage: cmp_abs(CC(1), CC(0))
2536
1
2537
sage: cmp_abs(CC(0), CC(0))
2538
0
2539
sage: cmp_abs(CC(2,1), CC(1,2))
2540
0
2541
"""
2542
if mpfr_zero_p(b.__re) and mpfr_zero_p(b.__im):
2543
return not ((mpfr_zero_p(a.__re) and mpfr_zero_p(a.__im)))
2544
elif (mpfr_zero_p(a.__re) and mpfr_zero_p(a.__im)):
2545
return -1
2546
cdef mp_exp_t exp_diff = max_exp(a) - max_exp(b)
2547
if exp_diff <= -2:
2548
return -1
2549
elif exp_diff >= 2:
2550
return 1
2551
2552
cdef int res
2553
cdef mpfr_t abs_a, abs_b, tmp
2554
mpfr_init2(abs_a, mpfr_get_prec(a.__re))
2555
mpfr_init2(abs_b, mpfr_get_prec(b.__re))
2556
mpfr_init2(tmp, mpfr_get_prec(a.__re))
2557
2558
mpfr_sqr(abs_a, a.__re, rnd)
2559
mpfr_sqr(tmp, a.__im, rnd)
2560
mpfr_add(abs_a, abs_a, tmp, rnd)
2561
2562
mpfr_sqr(abs_b, b.__re, rnd)
2563
mpfr_sqr(tmp, b.__im, rnd)
2564
mpfr_add(abs_b, abs_b, tmp, rnd)
2565
2566
res = mpfr_cmpabs(abs_a, abs_b)
2567
2568
mpfr_clear(abs_a)
2569
mpfr_clear(abs_b)
2570
mpfr_clear(tmp)
2571
2572
return res
2573
2574