Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagesmc
Path: blob/master/src/sage/rings/complex_mpc.pyx
8817 views
1
"""
2
Arbitrary Precision Complex Numbers using GNU MPC
3
4
This is a binding for the MPC arbitrary-precision floating point library.
5
It is adaptated from ``real_mpfr.pyx`` and ``complex_number.pyx``.
6
7
We define a class :class:`MPComplexField`, where each instance of
8
``MPComplexField`` specifies a field of floating-point complex numbers with
9
a specified precision shared by the real and imaginary part and a rounding
10
mode stating the rounding mode directions specific to real and imaginary
11
parts.
12
13
Individual floating-point numbers are of class :class:`MPComplexNumber`.
14
15
For floating-point representation and rounding mode description see the
16
documentation for the :mod:`sage.rings.real_mpfr`.
17
18
AUTHORS:
19
20
- Philippe Theveny (2008-10-13): initial version.
21
22
- Alex Ghitza (2008-11): cache, generators, random element, and many doctests.
23
24
- Yann Laigle-Chapuy (2010-01): improves compatibility with CC, updates.
25
26
- Jeroen Demeyer (2012-02): reformat documentation, make MPC a standard
27
package.
28
29
- Travis Scrimshaw (2012-10-18): Added doctests for full coverage.
30
31
EXAMPLES::
32
33
sage: MPC = MPComplexField(42)
34
sage: a = MPC(12, '15.64E+32'); a
35
12.0000000000 + 1.56400000000e33*I
36
sage: a *a *a *a
37
5.98338564121e132 - 1.83633318912e101*I
38
sage: a + 1
39
13.0000000000 + 1.56400000000e33*I
40
sage: a / 3
41
4.00000000000 + 5.21333333333e32*I
42
sage: MPC("infinity + NaN *I")
43
+infinity + NaN*I
44
"""
45
#*****************************************************************************
46
# Copyright (C) 2008 Philippe Theveny <[email protected]>
47
# 2008 Alex Ghitza
48
# 2010 Yann Laigle-Chapuy
49
# 2012 Jeroen Demeyer <[email protected]>
50
#
51
# Distributed under the terms of the GNU General Public License (GPL)
52
# as published by the Free Software Foundation; either version 2 of
53
# the License, or (at your option) any later version.
54
# http://www.gnu.org/licenses/
55
#*****************************************************************************
56
57
58
include "sage/ext/stdsage.pxi"
59
include 'sage/ext/interrupt.pxi'
60
61
import re
62
import sage.misc.misc
63
import complex_number
64
import complex_double
65
import field
66
import integer_ring
67
import integer
68
cimport integer
69
import real_mpfr
70
import weakref
71
import ring
72
73
from sage.structure.parent import Parent
74
from sage.structure.parent_gens import ParentWithGens
75
from sage.structure.element cimport RingElement, Element, ModuleElement
76
from sage.categories.map cimport Map
77
78
NumberFieldElement_quadratic = None
79
AlgebraicNumber_base = None
80
AlgebraicNumber = None
81
AlgebraicReal = None
82
AA = None
83
QQbar = None
84
CDF = CLF = RLF = None
85
86
def late_import():
87
"""
88
Import the objects/modules after build (when needed).
89
90
TESTS::
91
92
sage: sage.rings.complex_mpc.late_import()
93
"""
94
global NumberFieldElement_quadratic
95
global AlgebraicNumber_base
96
global AlgebraicNumber
97
global AlgebraicReal
98
global AA, QQbar
99
global CLF, RLF, CDF
100
if NumberFieldElement_quadratic is None:
101
import sage.rings.number_field.number_field_element_quadratic as nfeq
102
NumberFieldElement_quadratic = nfeq.NumberFieldElement_quadratic
103
import sage.rings.qqbar
104
AlgebraicNumber_base = sage.rings.qqbar.AlgebraicNumber_base
105
AlgebraicNumber = sage.rings.qqbar.AlgebraicNumber
106
AlgebraicReal = sage.rings.qqbar.AlgebraicReal
107
AA = sage.rings.qqbar.AA
108
QQbar = sage.rings.qqbar.QQbar
109
from real_lazy import CLF, RLF
110
from complex_double import CDF
111
112
from integer import Integer
113
from integer cimport Integer
114
from complex_number import ComplexNumber
115
from complex_number cimport ComplexNumber
116
from complex_field import ComplexField_class
117
118
from sage.misc.randstate cimport randstate, current_randstate
119
from real_mpfr cimport RealField_class, RealNumber
120
from real_mpfr import mpfr_prec_min, mpfr_prec_max
121
122
_mpfr_rounding_modes = ['RNDN', 'RNDZ', 'RNDU', 'RNDD']
123
124
_mpc_rounding_modes = [ 'RNDNN', 'RNDZN', 'RNDUN', 'RNDDN',
125
'', '', '', '', '', '', '', '', '', '', '', '',
126
'RNDNZ', 'RNDZZ', 'RNDUZ', 'RNDDZ',
127
'', '', '', '', '', '', '', '', '', '', '', '',
128
'RNDUN', 'RNDZU', 'RNDUU', 'RNDDU',
129
'', '', '', '', '', '', '', '', '', '', '', '',
130
'RNDDN', 'RNDZD', 'RNDUD', 'RNDDD' ]
131
132
cdef inline mpfr_rnd_t rnd_re(mpc_rnd_t rnd):
133
"""
134
Return the numeric value of the real part rounding mode. This
135
is an internal function.
136
"""
137
return <mpfr_rnd_t>(rnd & 3)
138
139
cdef inline mpfr_rnd_t rnd_im(mpc_rnd_t rnd):
140
"""
141
Return the numeric value of the imaginary part rounding mode.
142
This is an internal function.
143
"""
144
return <mpfr_rnd_t>(rnd >> 4)
145
146
sign = '[+-]'
147
digit_ten = '[0123456789]'
148
exponent_ten = '[e@]' + sign + '?[0123456789]+'
149
number_ten = 'inf(?:inity)?|@inf@|nan(?:\([0-9A-Z_]*\))?|@nan@(?:\([0-9A-Z_]*\))?'\
150
'|(?:' + digit_ten + '*\.' + digit_ten + '+|' + digit_ten + '+\.?)(?:' + exponent_ten + ')?'
151
imaginary_ten = 'i(?:\s*\*\s*(?:' + number_ten + '))?|(?:' + number_ten + ')\s*\*\s*i'
152
complex_ten = '(?P<im_first>(?P<im_first_im_sign>' + sign + ')?\s*(?P<im_first_im_abs>' + imaginary_ten + ')' \
153
'(\s*(?P<im_first_re_sign>' + sign + ')\s*(?P<im_first_re_abs>' + number_ten + '))?)' \
154
'|' \
155
'(?P<re_first>(?P<re_first_re_sign>' + sign + ')?\s*(?P<re_first_re_abs>' + number_ten + ')' \
156
'(\s*(?P<re_first_im_sign>' + sign + ')\s*(?P<re_first_im_abs>' + imaginary_ten + '))?)'
157
re_complex_ten = re.compile('^\s*(?:' + complex_ten + ')\s*$', re.I)
158
159
cpdef inline split_complex_string(string, int base=10):
160
"""
161
Split and return in that order the real and imaginary parts
162
of a complex in a string.
163
164
This is an internal function.
165
166
EXAMPLES::
167
168
sage: sage.rings.complex_mpc.split_complex_string('123.456e789')
169
('123.456e789', None)
170
sage: sage.rings.complex_mpc.split_complex_string('123.456e789*I')
171
(None, '123.456e789')
172
sage: sage.rings.complex_mpc.split_complex_string('123.+456e789*I')
173
('123.', '+456e789')
174
sage: sage.rings.complex_mpc.split_complex_string('123.456e789', base=2)
175
(None, None)
176
"""
177
if base == 10:
178
number = number_ten
179
z = re_complex_ten.match(string)
180
else:
181
all_digits = "0123456789abcdefghijklmnopqrstuvwxyz"
182
digit = '[' + all_digits[0:base] + ']'
183
184
# In MPFR, '1e42'-> 10^42, '1p42'->2^42, '1@42'->base^42
185
if base == 2:
186
exponent = '[e@p]'
187
elif base <= 10:
188
exponent = '[e@]'
189
elif base == 16:
190
exponent = '[@p]'
191
else:
192
exponent = '@'
193
exponent += sign + '?' + digit + '+'
194
195
# Warning: number, imaginary, and complex should be enclosed in parentheses
196
# when used as regexp because of alternatives '|'
197
number = '@nan@(?:\([0-9A-Z_]*\))?|@inf@|(?:' + digit + '*\.' + digit + '+|' + digit + '+\.?)(?:' + exponent + ')?'
198
if base <= 10:
199
number = 'nan(?:\([0-9A-Z_]*\))?|inf(?:inity)?|' + number
200
imaginary = 'i(?:\s*\*\s*(?:' + number + '))?|(?:' + number + ')\s*\*\s*i'
201
complex = '(?P<im_first>(?P<im_first_im_sign>' + sign + ')?\s*(?P<im_first_im_abs>' + imaginary + ')' \
202
'(\s*(?P<im_first_re_sign>' + sign + ')\s*(?P<im_first_re_abs>' + number + '))?)' \
203
'|' \
204
'(?P<re_first>(?P<re_first_re_sign>' + sign + ')?\s*(?P<re_first_re_abs>' + number + ')' \
205
'(\s*(?P<re_first_im_sign>' + sign + ')\s*(?P<re_first_im_abs>' + imaginary + '))?)'
206
207
z = re.match('^\s*(?:' + complex + ')\s*$', string, re.I)
208
209
x, y = None, None
210
if z is not None:
211
if z.group('im_first') is not None:
212
prefix = 'im_first'
213
elif z.group('re_first') is not None:
214
prefix = 're_first'
215
else:
216
return None
217
218
if z.group(prefix + '_re_abs') is not None:
219
x = z.expand('\g<' + prefix + '_re_abs>')
220
if z.group(prefix + '_re_sign') is not None:
221
x = z.expand('\g<' + prefix + '_re_sign>') + x
222
223
if z.group(prefix + '_im_abs') is not None:
224
y = re.search('(?P<im_part>' + number + ')', z.expand('\g<' + prefix + '_im_abs>'), re.I)
225
if y is None:
226
y = '1'
227
else:
228
y = y.expand('\g<im_part>')
229
if z.group(prefix + '_im_sign') is not None:
230
y = z.expand('\g<' + prefix + '_im_sign>') + y
231
232
return x, y
233
234
#*****************************************************************************
235
#
236
# MPComplex Field
237
#
238
#*****************************************************************************
239
# The complex field is in Cython, so mpc elements will have access to
240
# their parent via direct C calls, which will be faster.
241
242
cache = {}
243
def MPComplexField(prec=53, rnd="RNDNN", names=None):
244
"""
245
Return the complex field with real and imaginary parts having
246
prec *bits* of precision.
247
248
EXAMPLES::
249
250
sage: MPComplexField()
251
Complex Field with 53 bits of precision
252
sage: MPComplexField(100)
253
Complex Field with 100 bits of precision
254
sage: MPComplexField(100).base_ring()
255
Real Field with 100 bits of precision
256
sage: i = MPComplexField(200).gen()
257
sage: i^2
258
-1.0000000000000000000000000000000000000000000000000000000000
259
"""
260
global cache
261
mykey = (prec, rnd)
262
if cache.has_key(mykey):
263
X = cache[mykey]
264
C = X()
265
if not C is None:
266
return C
267
C = MPComplexField_class(prec, rnd)
268
cache[mykey] = weakref.ref(C)
269
return C
270
271
272
cdef class MPComplexField_class(sage.rings.ring.Field):
273
def __init__(self, int prec=53, rnd="RNDNN"):
274
"""
275
Initialize ``self``.
276
277
INPUT:
278
279
- ``prec`` -- (integer) precision; default = 53
280
281
prec is the number of bits used to represent the matissa of
282
both the real and imaginary part of complex floating-point number.
283
284
- ``rnd`` -- (string) the rounding mode; default = ``'RNDNN'``
285
286
Rounding mode is of the form ``'RNDxy'`` where ``x`` and ``y`` are
287
the rounding mode for respectively the real and imaginary parts and
288
are one of:
289
290
- ``'N'`` for rounding to nearest
291
- ``'Z'`` for rounding towards zero
292
- ``'U'`` for rounding towards plus infinity
293
- ``'D'`` for rounding towards minus infinity
294
295
For example, ``'RNDZU'`` indicates to round the real part towards
296
zero, and the imaginary part towards plus infinity.
297
298
EXAMPLES::
299
300
sage: MPComplexField(17)
301
Complex Field with 17 bits of precision
302
sage: MPComplexField()
303
Complex Field with 53 bits of precision
304
sage: MPComplexField(1042,'RNDDZ')
305
Complex Field with 1042 bits of precision and rounding RNDDZ
306
307
ALGORITHMS: Computations are done using the MPC library.
308
"""
309
if prec < mpfr_prec_min() or prec > mpfr_prec_max():
310
raise ValueError, "prec (=%s) must be >= %s and <= %s."%(
311
prec, mpfr_prec_min(), mpfr_prec_max())
312
self.__prec = prec
313
if not isinstance(rnd, str):
314
raise TypeError, "rnd must be a string"
315
try:
316
n = _mpc_rounding_modes.index(rnd)
317
except ValueError:
318
raise ValueError, "rnd (=%s) must be of the form RNDxy"\
319
"where x and y are one of N, Z, U, D"%rnd
320
self.__rnd = n
321
self.__rnd_str = rnd
322
323
self.__real_field = real_mpfr.RealField(prec, rnd=_mpfr_rounding_modes[rnd_re(n)])
324
self.__imag_field = real_mpfr.RealField(prec, rnd=_mpfr_rounding_modes[rnd_im(n)])
325
326
ParentWithGens.__init__(self, self._real_field(), ('I',), False)
327
self._populate_coercion_lists_(coerce_list=[MPFRtoMPC(self._real_field(), self)])
328
329
cdef MPComplexNumber _new(self):
330
"""
331
Return a new complex number with parent ``self`.
332
"""
333
cdef MPComplexNumber z
334
z = PY_NEW(MPComplexNumber)
335
z._parent = self
336
mpc_init2(z.value, self.__prec)
337
z.init = 1
338
return z
339
340
def _repr_ (self):
341
"""
342
Return a string representation of ``self``.
343
344
EXAMPLES::
345
346
sage: MPComplexField(200, 'RNDDU') # indirect doctest
347
Complex Field with 200 bits of precision and rounding RNDDU
348
"""
349
s = "Complex Field with %s bits of precision"%self.__prec
350
if self.__rnd != MPC_RNDNN:
351
s = s + " and rounding %s"%(self.__rnd_str)
352
return s
353
354
def _latex_(self):
355
r"""
356
Return a latex representation of ``self``.
357
358
EXAMPLES::
359
360
sage: MPC = MPComplexField(10)
361
sage: latex(MPC) # indirect doctest
362
\C
363
"""
364
return "\\C"
365
366
def __call__(self, x, im=None):
367
"""
368
Create a floating-point complex using ``x`` and optionally an imaginary
369
part ``im``.
370
371
EXAMPLES::
372
373
sage: MPC = MPComplexField()
374
sage: MPC(2) # indirect doctest
375
2.00000000000000
376
sage: MPC(0, 1) # indirect doctest
377
1.00000000000000*I
378
sage: MPC(1, 1)
379
1.00000000000000 + 1.00000000000000*I
380
sage: MPC(2, 3)
381
2.00000000000000 + 3.00000000000000*I
382
"""
383
if x is None:
384
return self.zero_element()
385
# We implement __call__ to gracefully accept the second argument.
386
if im is not None:
387
x = x, im
388
return Parent.__call__(self, x)
389
390
def _element_constructor_(self, z):
391
"""
392
Coerce `z` into this complex field.
393
394
EXAMPLES::
395
396
sage: C20 = MPComplexField(20) # indirect doctest
397
398
The value can be set with a couple of reals::
399
400
sage: a = C20(1.5625, 17.42); a
401
1.5625 + 17.420*I
402
sage: a.str(2)
403
'1.1001000000000000000 + 10001.011010111000011*I'
404
sage: C20(0, 2)
405
2.0000*I
406
407
Complex number can be coerced into MPComplexNumber::
408
409
sage: C20(14.7+0.35*I)
410
14.700 + 0.35000*I
411
sage: C20(i*4, 7)
412
Traceback (most recent call last):
413
...
414
TypeError: unable to coerce to a ComplexNumber: <type 'sage.symbolic.expression.Expression'>
415
416
Each part can be set with strings (written in base ten)::
417
418
sage: C20('1.234', '56.789')
419
1.2340 + 56.789*I
420
421
The string can represent the whole complex value::
422
423
sage: C20('42 + I * 100')
424
42.000 + 100.00*I
425
sage: C20('-42 * I')
426
- 42.000*I
427
428
The imaginary part can be written first::
429
430
sage: C20('100*i+42')
431
42.000 + 100.00*I
432
433
Use ``'inf'`` for infinity and ``'nan'`` for Not a Number::
434
435
sage: C20('nan+inf*i')
436
NaN + +infinity*I
437
"""
438
cdef MPComplexNumber zz
439
zz = self._new()
440
zz._set(z)
441
return zz
442
443
cpdef _coerce_map_from_(self, S):
444
"""
445
Canonical coercion of `z` to this mpc complex field.
446
447
The rings that canonically coerce to this mpc complex field are:
448
449
- any mpc complex field with precision that is as large as this one
450
- anything that canonically coerces to the mpfr real
451
field with this prec and the rounding mode of real part.
452
453
EXAMPLES::
454
455
sage: MPComplexField(100)(17, '4.2') + MPComplexField(20)('6.0', -23) # indirect doctest
456
23.000 - 18.800*I
457
sage: a = MPComplexField(100)(17, '4.2') + MPComplexField(20)('6.0', -23)
458
sage: a.parent()
459
Complex Field with 20 bits of precision
460
"""
461
if isinstance(S, RealField_class):
462
return MPFRtoMPC(S, self)
463
if isinstance(S, sage.rings.integer_ring.IntegerRing_class):
464
return INTEGERtoMPC(S, self)
465
466
RR = self.__real_field
467
if RR.has_coerce_map_from(S):
468
return self._coerce_map_via([RR], S)
469
470
if isinstance(S, MPComplexField_class) and S.prec() >= self.__prec:
471
#FIXME: What map when rounding modes differ but prec is the same ?
472
# How to provide commutativity of morphisms ?
473
# Change __cmp__ when done
474
return MPCtoMPC(S, self)
475
476
if isinstance(S, ComplexField_class) and S.prec() >= self.__prec:
477
return CCtoMPC(S, self)
478
479
late_import()
480
if S in [AA, QQbar, CLF, RLF] or (S == CDF and self._prec <= 53):
481
return self._generic_convert_map(S)
482
483
return self._coerce_map_via([CLF], S)
484
485
def __reduce__(self):
486
"""
487
For pickling.
488
489
EXAMPLES::
490
491
sage: C = MPComplexField(prec=200, rnd='RNDDZ')
492
sage: loads(dumps(C)) == C
493
True
494
"""
495
return __create__MPComplexField_version0, (self.__prec, self.__rnd_str)
496
497
def __cmp__(self, other):
498
"""
499
Compare ``self`` and ``other``.
500
501
EXAMPLES::
502
503
sage: MPComplexField(10) == MPComplexField(11) # indirect doctest
504
False
505
sage: MPComplexField(10) == MPComplexField(10)
506
True
507
sage: MPComplexField(10,rnd='RNDZN') == MPComplexField(10,rnd='RNDZU')
508
True
509
"""
510
if not isinstance(other, MPComplexField_class):
511
return -1
512
cdef MPComplexField_class _other
513
_other = other # to access C structure
514
#FIXME: if we choose a priority between rounding modes in
515
#order to provide commutativity of morphisms then rounding
516
#mode will matter
517
if self.__prec == _other.__prec: # and self.__rnd == _other.__rnd:
518
return 0
519
return 1
520
521
def gen(self, n=0):
522
"""
523
Return the generator of this complex field over its real subfield.
524
525
EXAMPLES::
526
527
sage: MPComplexField(34).gen()
528
1.00000000*I
529
"""
530
if n != 0:
531
raise IndexError, "n must be 0"
532
return self(0, 1)
533
534
def ngens(self):
535
"""
536
Return 1, the number of generators of this complex field over its real
537
subfield.
538
539
EXAMPLES::
540
541
sage: MPComplexField(34).ngens()
542
1
543
"""
544
return 1
545
546
cpdef _an_element_(self):
547
"""
548
Return an element of this complex field.
549
550
EXAMPLES::
551
552
sage: MPC = MPComplexField(20)
553
sage: MPC._an_element_()
554
1.0000*I
555
"""
556
return self(0, 1)
557
558
def random_element(self, min=0, max=1):
559
"""
560
Return a random complex number, uniformly distributed with
561
real and imaginary parts between min and max (default 0 to 1).
562
563
EXAMPLES::
564
565
sage: MPComplexField(100).random_element(-5, 10) # random
566
1.9305310520925994224072377281 + 0.94745292506956219710477444855*I
567
sage: MPComplexField(10).random_element() # random
568
0.12 + 0.23*I
569
"""
570
cdef MPComplexNumber z
571
z = self._new()
572
cdef randstate rstate = current_randstate()
573
mpc_urandom(z.value, rstate.gmp_state)
574
if min == 0 and max == 1:
575
return z
576
else:
577
return (max-min)*z + min*self(1,1)
578
579
cpdef bint is_exact(self): # except -2: # I don't know what this is for - TCS
580
"""
581
Returns whether or not this field is exact, which is always ``False``.
582
583
EXAMPLES::
584
585
sage: MPComplexField(42).is_exact()
586
False
587
"""
588
return False
589
590
def is_finite(self):
591
"""
592
Return ``False``, since the field of complex numbers is not finite.
593
594
EXAMPLES::
595
596
sage: MPComplexField(17).is_finite()
597
False
598
"""
599
return False
600
601
def characteristic(self):
602
"""
603
Return 0, since the field of complex numbers has characteristic 0.
604
605
EXAMPLES::
606
607
sage: MPComplexField(42).characteristic()
608
0
609
"""
610
return integer.Integer(0)
611
612
def name(self):
613
"""
614
Return the name of the complex field.
615
616
EXAMPLES::
617
618
sage: C = MPComplexField(10, 'RNDNZ'); C.name()
619
'MPComplexField10_RNDNZ'
620
"""
621
return "MPComplexField%s_%s"%(self.__prec, self.__rnd_str)
622
623
def __hash__(self):
624
"""
625
Return the hash of ``self``.
626
627
EXAMPLES::
628
629
sage: MPC = MPComplexField()
630
sage: hash(MPC) % 2^32 == hash(MPC.name()) % 2^32
631
True
632
"""
633
return hash(self.name())
634
635
def prec(self):
636
"""
637
Return the precision of this field of complex numbers.
638
639
EXAMPLES::
640
641
sage: MPComplexField().prec()
642
53
643
sage: MPComplexField(22).prec()
644
22
645
"""
646
return self.__prec
647
648
def rounding_mode(self):
649
"""
650
Return rounding modes used for each part of a complex number.
651
652
EXAMPLES::
653
654
sage: MPComplexField().rounding_mode()
655
'RNDNN'
656
sage: MPComplexField(rnd='RNDZU').rounding_mode()
657
'RNDZU'
658
"""
659
return self.__rnd_str
660
661
def rounding_mode_real(self):
662
"""
663
Return rounding mode used for the real part of complex number.
664
665
EXAMPLES::
666
667
sage: MPComplexField(rnd='RNDZU').rounding_mode_real()
668
'RNDZ'
669
"""
670
return _mpfr_rounding_modes[rnd_re(self.__rnd)]
671
672
def rounding_mode_imag(self):
673
"""
674
Return rounding mode used for the imaginary part of complex number.
675
676
EXAMPLES::
677
678
sage: MPComplexField(rnd='RNDZU').rounding_mode_imag()
679
'RNDU'
680
"""
681
return _mpfr_rounding_modes[rnd_im(self.__rnd)]
682
683
def _real_field(self):
684
"""
685
Return real field for the real part.
686
687
EXAMPLES::
688
689
sage: MPComplexField()._real_field()
690
Real Field with 53 bits of precision
691
"""
692
return self.__real_field
693
694
def _imag_field(self):
695
"""
696
Return real field for the imaginary part.
697
698
EXAMPLES::
699
700
sage: MPComplexField(prec=100)._imag_field()
701
Real Field with 100 bits of precision
702
"""
703
return self.__imag_field
704
705
706
#*****************************************************************************
707
#
708
# MPComplex Number -- element of MPComplex Field
709
#
710
#*****************************************************************************
711
712
cdef class MPComplexNumber(sage.structure.element.FieldElement):
713
"""
714
A floating point approximation to a complex number using any specified
715
precision common to both real and imaginary part.
716
"""
717
cdef MPComplexNumber _new(self):
718
"""
719
Return a new complex number with same parent as ``self``.
720
"""
721
cdef MPComplexNumber z
722
z = PY_NEW(MPComplexNumber)
723
z._parent = self._parent
724
mpc_init2(z.value, (<MPComplexField_class>self._parent).__prec)
725
z.init = 1
726
return z
727
728
def __init__(self, MPComplexField_class parent, x, y=None, int base=10):
729
"""
730
Create a complex number.
731
732
INPUT:
733
734
- ``x`` -- real part or the complex value in a string
735
736
- ``y`` -- imaginary part
737
738
- ``base`` -- when ``x`` or ``y`` is a string, base in which the
739
number is written
740
741
A :class:`MPComplexNumber` should be called by first creating a
742
:class:`MPComplexField`, as illustrated in the examples.
743
744
EXAMPLES::
745
746
sage: C200 = MPComplexField(200)
747
sage: C200(1/3, '0.6789')
748
0.33333333333333333333333333333333333333333333333333333333333 + 0.67890000000000000000000000000000000000000000000000000000000*I
749
sage: C3 = MPComplexField(3)
750
sage: C3('1.2345', '0.6789')
751
1.2 + 0.62*I
752
sage: C3(3.14159)
753
3.0
754
755
Rounding modes::
756
757
sage: w = C3(5/2, 7/2); w.str(2)
758
'10.1 + 11.1*I'
759
sage: MPComplexField(2, rnd="RNDZN")(w).str(2)
760
'10. + 100.*I'
761
sage: MPComplexField(2, rnd="RNDDU")(w).str(2)
762
'10. + 100.*I'
763
sage: MPComplexField(2, rnd="RNDUD")(w).str(2)
764
'11. + 11.*I'
765
sage: MPComplexField(2, rnd="RNDNZ")(w).str(2)
766
'10. + 11.*I'
767
768
TESTS::
769
770
sage: MPComplexField(42)._repr_option('element_is_atomic')
771
False
772
"""
773
self.init = 0
774
if parent is None:
775
raise TypeError
776
self._parent = parent
777
mpc_init2(self.value, parent.__prec)
778
self.init = 1
779
if x is None: return
780
self._set(x, y, base)
781
782
def _set(self, z, y=None, base=10):
783
"""
784
EXAMPLES::
785
786
sage: MPC = MPComplexField(100)
787
sage: r = RealField(100).pi()
788
sage: z = MPC(r); z # indirect doctest
789
3.1415926535897932384626433833
790
sage: MPComplexField(10, rnd='RNDDD')(z)
791
3.1
792
sage: c = ComplexField(53)(1, r)
793
sage: MPC(c)
794
1.0000000000000000000000000000 + 3.1415926535897931159979634685*I
795
sage: MPC(I)
796
1.0000000000000000000000000000*I
797
sage: MPC('-0 +i')
798
1.0000000000000000000000000000*I
799
sage: MPC(1+i)
800
1.0000000000000000000000000000 + 1.0000000000000000000000000000*I
801
sage: MPC(1/3)
802
0.33333333333333333333333333333
803
804
::
805
806
sage: MPC(1, r/3)
807
1.0000000000000000000000000000 + 1.0471975511965977461542144611*I
808
sage: MPC(3, 2)
809
3.0000000000000000000000000000 + 2.0000000000000000000000000000*I
810
sage: MPC(0, r)
811
3.1415926535897932384626433833*I
812
sage: MPC('0.625e-26', '0.0000001')
813
6.2500000000000000000000000000e-27 + 1.0000000000000000000000000000e-7*I
814
"""
815
# This should not be called except when the number is being created.
816
# Complex Numbers are supposed to be immutable.
817
cdef RealNumber x
818
cdef mpc_rnd_t rnd
819
rnd =(<MPComplexField_class>self._parent).__rnd
820
if y is None:
821
if z is None: return
822
if PY_TYPE_CHECK(z, MPComplexNumber):
823
mpc_set(self.value, (<MPComplexNumber>z).value, rnd)
824
return
825
elif PY_TYPE_CHECK(z, str):
826
a, b = split_complex_string(z, base)
827
# set real part
828
if a is None:
829
mpfr_set_ui(self.value.re, 0, GMP_RNDN)
830
else:
831
mpfr_set_str(self.value.re, a, base, rnd_re(rnd))
832
# set imag part
833
if b is None:
834
if a is None:
835
raise TypeError, "Unable to convert z (='%s') to a MPComplexNumber." %z
836
else:
837
mpfr_set_str(self.value.im, b, base, rnd_im(rnd))
838
return
839
elif PY_TYPE_CHECK(z, ComplexNumber):
840
mpc_set_fr_fr(self.value, (<ComplexNumber>z).__re, (<ComplexNumber>z).__im, rnd)
841
return
842
elif isinstance(z, sage.libs.pari.all.pari_gen):
843
real, imag = z.real(), z.imag()
844
elif isinstance(z, list) or isinstance(z, tuple):
845
real, imag = z
846
elif isinstance(z, complex):
847
real, imag = z.real, z.imag
848
elif isinstance(z, sage.symbolic.expression.Expression):
849
zz = sage.rings.complex_field.ComplexField(self._parent.prec())(z)
850
self._set(zz)
851
return
852
# then, no imaginary part
853
elif PY_TYPE_CHECK(z, RealNumber):
854
zz = sage.rings.real_mpfr.RealField(self._parent.prec())(z)
855
mpc_set_fr(self.value, (<RealNumber>zz).value, rnd)
856
return
857
elif PY_TYPE_CHECK(z, Integer):
858
mpc_set_z(self.value, (<Integer>z).value, rnd)
859
return
860
elif isinstance(z, (int, long)):
861
mpc_set_si(self.value, z, rnd)
862
return
863
else:
864
real = z
865
imag = 0
866
else:
867
real = z
868
imag = y
869
870
cdef RealField_class R = self._parent._real_field()
871
try:
872
rr = R(real)
873
ii = R(imag)
874
mpc_set_fr_fr(self.value, (<RealNumber>rr).value, (<RealNumber>ii).value, rnd)
875
876
except TypeError:
877
raise TypeError, "unable to coerce to a ComplexNumber: %s" % type(real)
878
879
def __reduce__(self):
880
"""
881
For pickling.
882
883
EXAMPLES::
884
885
sage: C = MPComplexField(prec=200, rnd='RNDUU')
886
sage: b = C(393.39203845902384098234098230948209384028340)
887
sage: loads(dumps(b)) == b;
888
True
889
sage: C(1)
890
1.0000000000000000000000000000000000000000000000000000000000
891
sage: b = C(1)/C(0); b
892
NaN + NaN*I
893
sage: loads(dumps(b)) == b
894
True
895
sage: b = C(-1)/C(0.); b
896
NaN + NaN*I
897
sage: loads(dumps(b)) == b
898
True
899
sage: b = C(-1).sqrt(); b
900
1.0000000000000000000000000000000000000000000000000000000000*I
901
sage: loads(dumps(b)) == b
902
True
903
"""
904
s = self.str(32)
905
return (__create_MPComplexNumber_version0, (self._parent, s, 32))
906
907
def __dealloc__(self):
908
if self.init:
909
mpc_clear(self.value)
910
911
def _repr_(self):
912
"""
913
Return a string representation of ``self``.
914
915
EXAMPLES::
916
917
sage: MPComplexField()(2, -3) # indirect doctest
918
2.00000000000000 - 3.00000000000000*I
919
"""
920
return self.str()
921
922
def _latex_(self):
923
"""
924
Return a latex representation of ``self``.
925
926
EXAMPLES::
927
928
sage: latex(MPComplexField()(2, -3)) # indirect doctest
929
2.00000000000000 - 3.00000000000000i
930
"""
931
import re
932
s = self.str().replace('*I', 'i')
933
return re.sub(r"e(-?\d+)", r" \\times 10^{\1}", s)
934
935
def __hash__(self):
936
"""
937
Returns the hash of ``self``, which coincides with the python
938
complex and float (and often int) types.
939
940
This has the drawback that two very close high precision
941
numbers will have the same hash, but allows them to play
942
nicely with other real types.
943
944
EXAMPLES::
945
946
sage: hash(MPComplexField()('1.2', 33)) == hash(complex(1.2, 33))
947
True
948
"""
949
return hash(complex(self))
950
951
def __getitem__(self, i):
952
r"""
953
Returns either the real or imaginary component of ``self``
954
depending on the choice of ``i``: real (``i``=0), imaginary (``i``=1).
955
956
INPUTS:
957
958
- ``i`` -- 0 or 1
959
960
- ``0`` -- will return the real component of ``self``
961
- ``1`` -- will return the imaginary component of ``self``
962
963
EXAMPLES::
964
965
sage: MPC = MPComplexField()
966
sage: a = MPC(2,1)
967
sage: a.__getitem__(0)
968
2.00000000000000
969
sage: a.__getitem__(1)
970
1.00000000000000
971
972
::
973
974
sage: b = MPC(42,0)
975
sage: b
976
42.0000000000000
977
sage: b.__getitem__(1)
978
0.000000000000000
979
"""
980
if i == 0:
981
return self.real()
982
elif i == 1:
983
return self.imag()
984
raise IndexError, "i must be between 0 and 1."
985
986
def prec(self):
987
"""
988
Return precision of this complex number.
989
990
EXAMPLES::
991
992
sage: i = MPComplexField(2000).0
993
sage: i.prec()
994
2000
995
"""
996
return <MPComplexField_class>(self._parent).__prec
997
998
def real(self):
999
"""
1000
Return the real part of ``self``.
1001
1002
EXAMPLES::
1003
1004
sage: C = MPComplexField(100)
1005
sage: z = C(2, 3)
1006
sage: x = z.real(); x
1007
2.0000000000000000000000000000
1008
sage: x.parent()
1009
Real Field with 100 bits of precision
1010
"""
1011
cdef RealNumber x
1012
x = RealNumber(self._parent._real_field())
1013
mpfr_set (x.value, self.value.re, (<RealField_class>x._parent).rnd)
1014
return x
1015
1016
def imag(self):
1017
"""
1018
Return imaginary part of ``self``.
1019
1020
EXAMPLES::
1021
1022
sage: C = MPComplexField(100)
1023
sage: z = C(2, 3)
1024
sage: x = z.imag(); x
1025
3.0000000000000000000000000000
1026
sage: x.parent()
1027
Real Field with 100 bits of precision
1028
"""
1029
cdef RealNumber y
1030
y = RealNumber(self._parent._imag_field())
1031
mpfr_set (y.value, self.value.im, (<RealField_class>y._parent).rnd)
1032
return y
1033
1034
def parent(self):
1035
"""
1036
Return the complex field containing the number.
1037
1038
EXAMPLES::
1039
1040
sage: C = MPComplexField()
1041
sage: a = C(1.2456, 987.654)
1042
sage: a.parent()
1043
Complex Field with 53 bits of precision
1044
"""
1045
return self._parent
1046
1047
def str(self, int base=10, int truncate=True):
1048
"""
1049
Return a string of ``self``.
1050
1051
INPUT:
1052
1053
- ``base`` -- base for output
1054
1055
- ``truncate`` -- if ``True``, round off the last digits in printing
1056
to lessen confusing base-2 roundoff issues.
1057
1058
EXAMPLES::
1059
1060
sage: MPC = MPComplexField(64)
1061
sage: z = MPC(-4, 3)/7
1062
sage: z.str()
1063
'-0.571428571428571429 + 0.428571428571428571*I'
1064
sage: z.str(16)
1065
'-0.92492492492492490 + 0.6db6db6db6db6db70*I'
1066
sage: z.str(truncate=True)
1067
'-0.571428571428571429 + 0.428571428571428571*I'
1068
sage: z.str(2, True)
1069
'-0.1001001001001001001001001001001001001001001001001001001001001001 + 0.01101101101101101101101101101101101101101101101101101101101101110*I'
1070
"""
1071
s = ""
1072
if self.real() != 0:
1073
s = self.real().str(base, truncate=truncate)
1074
if self.imag() != 0:
1075
if mpfr_signbit(self.value.im):
1076
s += ' - ' + (-self.imag()).str(base, truncate=truncate) + '*I'
1077
else:
1078
if s:
1079
s += ' + '
1080
s += self.imag().str(base, truncate=truncate) + '*I'
1081
if not s:
1082
return "0"
1083
return s
1084
1085
def __copy__(self):
1086
"""
1087
Return copy of ``self``.
1088
1089
Since ``self`` is immutable, we just return ``self`` again.
1090
1091
EXAMPLES::
1092
1093
sage: a = MPComplexField()(3.5, 3)
1094
sage: copy(a) is a
1095
True
1096
"""
1097
return self # since object is immutable.
1098
1099
def __int__(self):
1100
r"""
1101
Method for converting ``self`` to type ``int``.
1102
1103
Called by the ``int`` function. Note that calling this method returns
1104
an error since, in general, complex numbers cannot be coerced into
1105
integers.
1106
1107
EXAMPLES::
1108
1109
sage: MPC = MPComplexField()
1110
sage: a = MPC(2,1)
1111
sage: int(a)
1112
Traceback (most recent call last):
1113
...
1114
TypeError: can't convert complex to int; use int(abs(z))
1115
sage: a.__int__()
1116
Traceback (most recent call last):
1117
...
1118
TypeError: can't convert complex to int; use int(abs(z))
1119
"""
1120
raise TypeError, "can't convert complex to int; use int(abs(z))"
1121
1122
def __long__(self):
1123
r"""
1124
Method for converting ``self`` to type ``long``.
1125
1126
Called by the ``long`` function. Note that calling this method
1127
returns an error since, in general, complex numbers cannot be
1128
coerced into integers.
1129
1130
EXAMPLES::
1131
1132
sage: MPC = MPComplexField()
1133
sage: a = MPC(2,1)
1134
sage: long(a)
1135
Traceback (most recent call last):
1136
...
1137
TypeError: can't convert complex to long; use long(abs(z))
1138
sage: a.__long__()
1139
Traceback (most recent call last):
1140
...
1141
TypeError: can't convert complex to long; use long(abs(z))
1142
"""
1143
raise TypeError, "can't convert complex to long; use long(abs(z))"
1144
1145
def __float__(self):
1146
r"""
1147
Method for converting ``self`` to type ``float``.
1148
1149
Called by the ``float`` function. Note that calling this method returns
1150
an error since if the imaginary part of the number is not zero.
1151
1152
EXAMPLES::
1153
1154
sage: MPC = MPComplexField()
1155
sage: a = MPC(1, 0)
1156
sage: float(a)
1157
1.0
1158
sage: a = MPC(2,1)
1159
sage: float(a)
1160
Traceback (most recent call last):
1161
...
1162
TypeError: can't convert complex to float; use abs(z)
1163
sage: a.__float__()
1164
Traceback (most recent call last):
1165
...
1166
TypeError: can't convert complex to float; use abs(z)
1167
"""
1168
if mpfr_zero_p(self.value.im):
1169
return mpfr_get_d(self.value.re,\
1170
rnd_re((<MPComplexField_class>self._parent).__rnd))
1171
else:
1172
raise TypeError, "can't convert complex to float; use abs(z)"
1173
1174
def __complex__(self):
1175
r"""
1176
Method for converting ``self`` to type ``complex``.
1177
1178
Called by the ``complex`` function.
1179
1180
EXAMPLES::
1181
1182
sage: MPC = MPComplexField()
1183
sage: a = MPC(2,1)
1184
sage: complex(a)
1185
(2+1j)
1186
sage: type(complex(a))
1187
<type 'complex'>
1188
sage: a.__complex__()
1189
(2+1j)
1190
"""
1191
# Fixme: is it the right choice for rounding modes ?
1192
cdef mpc_rnd_t rnd
1193
rnd = (<MPComplexField_class>self._parent).__rnd
1194
return complex(mpfr_get_d(self.value.re, rnd_re(rnd)), mpfr_get_d(self.value.im, rnd_im(rnd)))
1195
1196
def __cmp__(self, other):
1197
r"""
1198
Compare ``self`` to ``other``.
1199
1200
EXAMPLES::
1201
1202
sage: MPC = MPComplexField()
1203
sage: a = MPC(2,1)
1204
sage: b = MPC(1,2)
1205
sage: a < b
1206
False
1207
sage: a > b
1208
True
1209
"""
1210
cdef MPComplexNumber z = <MPComplexNumber>other
1211
# NaN should compare to nothing
1212
if mpfr_nan_p (self.value.re) or mpfr_nan_p (self.value.im) or mpfr_nan_p (z.value.re) or mpfr_nan_p (z.value.im):
1213
return False
1214
cdef int c = mpc_cmp(self.value, z.value)
1215
cdef int cre = MPC_INEX_RE(c)
1216
cdef int cim
1217
if cre:
1218
if cre>0: return 1
1219
else: return -1
1220
else:
1221
cim = MPC_INEX_IM(c)
1222
if cim>0: return 1
1223
elif cim<0: return -1
1224
else: return 0
1225
1226
def __nonzero__(self):
1227
"""
1228
Return ``True`` if ``self`` is not zero.
1229
1230
This is an internal function; use :meth:`is_zero()` instead.
1231
1232
EXAMPLES::
1233
1234
sage: MPC = MPComplexField()
1235
sage: z = 1 + MPC(I)
1236
sage: z.is_zero()
1237
False
1238
"""
1239
return not (mpfr_zero_p(self.value.re) and mpfr_zero_p(self.value.im))
1240
1241
def is_square(self):
1242
r"""
1243
This function always returns true as `\CC` is algebraically closed.
1244
1245
EXAMPLES::
1246
1247
sage: C200 = MPComplexField(200)
1248
sage: a = C200(2,1)
1249
sage: a.is_square()
1250
True
1251
1252
`\CC` is algebraically closed, hence every element is a square::
1253
1254
sage: b = C200(5)
1255
sage: b.is_square()
1256
True
1257
"""
1258
return True
1259
1260
def is_real(self):
1261
"""
1262
Return ``True`` if ``self`` is real, i.e. has imaginary part zero.
1263
1264
EXAMPLES::
1265
1266
sage: C200 = MPComplexField(200)
1267
sage: C200(1.23).is_real()
1268
True
1269
sage: C200(1+i).is_real()
1270
False
1271
"""
1272
return (mpfr_zero_p(self.value.im) != 0)
1273
1274
def is_imaginary(self):
1275
"""
1276
Return ``True`` if ``self`` is imaginary, i.e. has real part zero.
1277
1278
EXAMPLES::
1279
1280
sage: C200 = MPComplexField(200)
1281
sage: C200(1.23*i).is_imaginary()
1282
True
1283
sage: C200(1+i).is_imaginary()
1284
False
1285
"""
1286
return (mpfr_zero_p(self.value.re) != 0)
1287
1288
def algebraic_dependency(self, n, **kwds):
1289
"""
1290
Returns a polynomial of degree at most `n` which is
1291
approximately satisfied by this complex number. Note that the
1292
returned polynomial need not be irreducible, and indeed usually
1293
won't be if `z` is a good approximation to an algebraic
1294
number of degree less than `n`.
1295
1296
ALGORITHM: Uses the PARI C-library algdep command.
1297
1298
INPUT: Type ``algdep?`` at the top level prompt. All additional
1299
parameters are passed onto the top-level algdep command.
1300
1301
EXAMPLES::
1302
1303
sage: MPC = MPComplexField()
1304
sage: z = (1/2)*(1 + sqrt(3.0) * MPC.0); z
1305
0.500000000000000 + 0.866025403784439*I
1306
sage: p = z.algebraic_dependency(5)
1307
sage: p.factor()
1308
(x + 1) * (x^2 - x + 1)^2
1309
sage: z^2 - z + 1
1310
1.11022302462516e-16
1311
"""
1312
import sage.rings.arith
1313
return sage.rings.arith.algdep(self,n, **kwds)
1314
1315
# Former misspelling
1316
algebraic_dependancy = algebraic_dependency
1317
1318
################################
1319
# Basic Arithmetic
1320
################################
1321
1322
cpdef ModuleElement _add_(self, ModuleElement right):
1323
"""
1324
Add two complex numbers with the same parent.
1325
1326
EXAMPLES::
1327
1328
sage: MPC = MPComplexField(30)
1329
sage: MPC(-1.5, 2) + MPC(0.2, 1) # indirect doctest
1330
-1.3000000 + 3.0000000*I
1331
"""
1332
cdef MPComplexNumber z
1333
z = self._new()
1334
mpc_add(z.value, self.value, (<MPComplexNumber>right).value, (<MPComplexField_class>self._parent).__rnd)
1335
return z
1336
1337
cpdef ModuleElement _sub_(self, ModuleElement right):
1338
"""
1339
Subtract two complex numbers with the same parent.
1340
1341
EXAMPLES::
1342
1343
sage: MPC = MPComplexField(30)
1344
sage: MPC(-1.5, 2) - MPC(0.2, 1) # indirect doctest
1345
-1.7000000 + 1.0000000*I
1346
"""
1347
cdef MPComplexNumber z
1348
z = self._new()
1349
mpc_sub(z.value, self.value, (<MPComplexNumber>right).value, (<MPComplexField_class>self._parent).__rnd)
1350
return z
1351
1352
cpdef RingElement _mul_(self, RingElement right):
1353
"""
1354
Multiply two complex numbers with the same parent.
1355
1356
EXAMPLES::
1357
1358
sage: MPC = MPComplexField(30)
1359
sage: MPC(-1.5, 2) * MPC(0.2, 1) # indirect doctest
1360
-2.3000000 - 1.1000000*I
1361
"""
1362
cdef MPComplexNumber z
1363
z = self._new()
1364
mpc_mul(z.value, self.value, (<MPComplexNumber>right).value, (<MPComplexField_class>self._parent).__rnd)
1365
return z
1366
1367
cpdef RingElement _div_(self, RingElement right):
1368
"""
1369
Divide two complex numbers with the same parent.
1370
1371
EXAMPLES::
1372
1373
sage: MPC = MPComplexField(30)
1374
sage: MPC(-1.5, 2) / MPC(0.2, 1) # indirect doctest
1375
1.6346154 + 1.8269231*I
1376
sage: MPC(-1, 1) / MPC(0)
1377
NaN + NaN*I
1378
"""
1379
cdef MPComplexNumber z, x
1380
z = self._new()
1381
x = <MPComplexNumber>right
1382
if not x.is_zero():
1383
mpc_div(z.value, self.value, x.value, (<MPComplexField_class>self._parent).__rnd)
1384
return z
1385
1386
cpdef ModuleElement _neg_(self):
1387
"""
1388
Return the negative of this complex number.
1389
1390
EXAMPLES::
1391
1392
sage: MPC = MPComplexField(30)
1393
sage: - MPC(-1.5, 2) # indirect doctest
1394
1.5000000 - 2.0000000*I
1395
sage: - MPC(0)
1396
0
1397
"""
1398
cdef MPComplexNumber z
1399
z = self._new()
1400
mpc_neg(z.value, self.value, (<MPComplexField_class>self._parent).__rnd)
1401
return z
1402
1403
def __invert__(self):
1404
"""
1405
Return the multiplicative inverse.
1406
1407
EXAMPLES::
1408
1409
sage: C = MPComplexField()
1410
sage: a = ~C(5, 1)
1411
sage: a * C(5, 1)
1412
1.00000000000000
1413
"""
1414
cdef MPComplexNumber z
1415
z = self._new()
1416
if not self.is_zero():
1417
mpc_ui_div (z.value, 1, self.value, (<MPComplexField_class>self._parent).__rnd)
1418
return z
1419
1420
def __neg__(self):
1421
r"""
1422
Return the negative of this complex number.
1423
1424
-(a + ib) = -a -i b
1425
1426
EXAMPLES::
1427
1428
sage: MPC = MPComplexField()
1429
sage: a = MPC(2,1)
1430
sage: -a
1431
-2.00000000000000 - 1.00000000000000*I
1432
sage: a.__neg__()
1433
-2.00000000000000 - 1.00000000000000*I
1434
"""
1435
cdef MPComplexNumber z
1436
z = self._new()
1437
mpc_neg(z.value, self.value, (<MPComplexField_class>self._parent).__rnd)
1438
return z
1439
1440
def __abs__(self):
1441
r"""
1442
Absolute value or modulus of this complex number,
1443
rounded with the rounding mode of the real part:
1444
1445
.. MATH::
1446
1447
|a + ib| = \sqrt(a^2 + b^2).
1448
1449
OUTPUT:
1450
1451
A floating-point number in the real field of the real part
1452
(same precision, same rounding mode).
1453
1454
EXAMPLES:
1455
1456
Note that the absolute value of a complex number with imaginary
1457
component equal to zero is the absolute value of the real component::
1458
1459
sage: MPC = MPComplexField()
1460
sage: a = MPC(2,1)
1461
sage: abs(a)
1462
2.23606797749979
1463
sage: a.__abs__()
1464
2.23606797749979
1465
sage: float(sqrt(2^2 + 1^1))
1466
2.23606797749979
1467
1468
sage: b = MPC(42,0)
1469
sage: abs(b)
1470
42.0000000000000
1471
sage: b.__abs__()
1472
42.0000000000000
1473
sage: b
1474
42.0000000000000
1475
"""
1476
cdef RealNumber x
1477
x = RealNumber(self._parent._real_field())
1478
mpc_abs (x.value, self.value, (<RealField_class>x._parent).rnd)
1479
return x
1480
1481
def norm(self):
1482
r"""
1483
Return the norm of a complex number, rounded with the rounding
1484
mode of the real part. The norm is the square of the absolute
1485
value:
1486
1487
.. MATH::
1488
1489
\mathrm{norm}(a + ib) = a^2 + b^2.
1490
1491
OUTPUT:
1492
1493
A floating-point number in the real field of the real part
1494
(same precision, same rounding mode).
1495
1496
EXAMPLES:
1497
1498
This indeed acts as the square function when the imaginary
1499
component of self is equal to zero::
1500
1501
sage: MPC = MPComplexField()
1502
sage: a = MPC(2,1)
1503
sage: a.norm()
1504
5.00000000000000
1505
sage: b = MPC(4.2,0)
1506
sage: b.norm()
1507
17.6400000000000
1508
sage: b^2
1509
17.6400000000000
1510
"""
1511
cdef RealNumber x
1512
x = RealNumber(self._parent._real_field())
1513
mpc_norm(x.value, self.value, (<RealField_class>x._parent).rnd)
1514
return x
1515
1516
def __rdiv__(self, left):
1517
r"""
1518
Returns the quotient of ``left`` with ``self``, that is: ``left/self``
1519
as a complex number.
1520
1521
INPUT:
1522
1523
- ``left`` -- a complex number
1524
1525
EXAMPLES::
1526
1527
sage: MPC = MPComplexField()
1528
sage: a = MPC(2, 2)
1529
sage: a.__rdiv__(MPC(1))
1530
0.250000000000000 - 0.250000000000000*I
1531
sage: MPC(1)/a
1532
0.250000000000000 - 0.250000000000000*I
1533
"""
1534
return MPComplexNumber(self._parent, left)/self
1535
1536
def __pow__(self, right, modulus):
1537
"""
1538
Compute ``self`` raised to the power of exponent, rounded in
1539
the direction specified by the parent of ``self``.
1540
1541
.. TODO:
1542
1543
FIXME: Branch cut
1544
1545
EXAMPLES::
1546
1547
sage: MPC.<i> = MPComplexField(20)
1548
sage: a = i^2; a
1549
-1.0000
1550
sage: a.parent()
1551
Complex Field with 20 bits of precision
1552
sage: a = (1+i)^i; a
1553
0.42883 + 0.15487*I
1554
sage: (1+i)^(1+i)
1555
0.27396 + 0.58370*I
1556
sage: a.parent()
1557
Complex Field with 20 bits of precision
1558
sage: i^i
1559
0.20788
1560
sage: (2+i)^(0.5)
1561
1.4553 + 0.34356*I
1562
"""
1563
cdef MPComplexNumber z, x, p
1564
x = <MPComplexNumber>self
1565
z = x._new()
1566
1567
if isinstance(right, (int,long)):
1568
mpc_pow_si(z.value, x.value, right, (<MPComplexField_class>x._parent).__rnd)
1569
elif isinstance(right, Integer):
1570
mpc_pow_z(z.value, x.value, (<Integer>right).value, (<MPComplexField_class>x._parent).__rnd)
1571
else:
1572
try:
1573
p = (<MPComplexField_class>x._parent)(right)
1574
except Exception:
1575
raise ValueError
1576
mpc_pow(z.value, x.value, p.value, (<MPComplexField_class>x._parent).__rnd)
1577
1578
return z
1579
1580
################################
1581
# Trigonometric & hyperbolic functions
1582
################################
1583
1584
def cos(self):
1585
r"""
1586
Return the cosine of this complex number:
1587
1588
.. MATH::
1589
1590
\cos(a + ib) = \cos a \cosh b -i \sin a \sinh b.
1591
1592
EXAMPLES::
1593
1594
sage: MPC = MPComplexField()
1595
sage: u = MPC(2, 4)
1596
sage: cos(u)
1597
-11.3642347064011 - 24.8146514856342*I
1598
"""
1599
cdef MPComplexNumber z
1600
z = self._new()
1601
mpc_cos (z.value, self.value, (<MPComplexField_class>self._parent).__rnd)
1602
return z
1603
1604
def sin(self):
1605
r"""
1606
Return the sine of this complex number:
1607
1608
.. MATH::
1609
1610
\sin(a + ib) = \sin a \cosh b + i \cos x \sinh b.
1611
1612
EXAMPLES::
1613
1614
sage: MPC = MPComplexField()
1615
sage: u = MPC(2, 4)
1616
sage: sin(u)
1617
24.8313058489464 - 11.3566127112182*I
1618
"""
1619
cdef MPComplexNumber z
1620
z = self._new()
1621
mpc_sin (z.value, self.value, (<MPComplexField_class>self._parent).__rnd)
1622
return z
1623
1624
def tan(self):
1625
r"""
1626
Return the tangent of this complex number:
1627
1628
.. MATH::
1629
1630
\tan(a + ib) = (\sin 2a + i \sinh 2b)/(\cos 2a + \cosh 2b).
1631
1632
EXAMPLES::
1633
1634
sage: MPC = MPComplexField()
1635
sage: u = MPC(-2, 4)
1636
sage: tan(u)
1637
0.000507980623470039 + 1.00043851320205*I
1638
"""
1639
cdef MPComplexNumber z
1640
z = self._new()
1641
mpc_tan (z.value, self.value, (<MPComplexField_class>self._parent).__rnd)
1642
return z
1643
1644
def cosh(self):
1645
"""
1646
Return the hyperbolic cosine of this complex number:
1647
1648
.. MATH::
1649
1650
\cosh(a + ib) = \cosh a \cos b + i \sinh a \sin b.
1651
1652
EXAMPLES::
1653
1654
sage: MPC = MPComplexField()
1655
sage: u = MPC(2, 4)
1656
sage: cosh(u)
1657
-2.45913521391738 - 2.74481700679215*I
1658
"""
1659
cdef MPComplexNumber z
1660
z = self._new()
1661
mpc_cosh (z.value, self.value, (<MPComplexField_class>self._parent).__rnd)
1662
return z
1663
1664
def sinh(self):
1665
"""
1666
Return the hyperbolic sine of this complex number:
1667
1668
.. MATH::
1669
1670
\sinh(a + ib) = \sinh a \cos b + i \cosh a \sin b.
1671
1672
EXAMPLES::
1673
1674
sage: MPC = MPComplexField()
1675
sage: u = MPC(2, 4)
1676
sage: sinh(u)
1677
-2.37067416935200 - 2.84723908684883*I
1678
"""
1679
cdef MPComplexNumber z
1680
z = self._new()
1681
mpc_sinh (z.value, self.value, (<MPComplexField_class>self._parent).__rnd)
1682
return z
1683
1684
def tanh(self):
1685
r"""
1686
Return the hyperbolic tangent of this complex number:
1687
1688
.. MATH::
1689
1690
\tanh(a + ib) = (\sinh 2a + i \sin 2b)/(\cosh 2a + \cos 2b).
1691
1692
EXAMPLES::
1693
1694
sage: MPC = MPComplexField()
1695
sage: u = MPC(2, 4)
1696
sage: tanh(u)
1697
1.00468231219024 + 0.0364233692474037*I
1698
"""
1699
cdef MPComplexNumber z
1700
z = self._new()
1701
mpc_tanh (z.value, self.value, (<MPComplexField_class>self._parent).__rnd)
1702
return z
1703
1704
def arccos(self):
1705
"""
1706
Return the arccosine of this complex number.
1707
1708
EXAMPLES::
1709
1710
sage: MPC = MPComplexField()
1711
sage: u = MPC(2, 4)
1712
sage: arccos(u)
1713
1.11692611683177 - 2.19857302792094*I
1714
"""
1715
cdef MPComplexNumber z
1716
z = self._new()
1717
mpc_acos (z.value, self.value, (<MPComplexField_class>self._parent).__rnd)
1718
return z
1719
1720
def arcsin(self):
1721
"""
1722
Return the arcsine of this complex number.
1723
1724
EXAMPLES::
1725
1726
sage: MPC = MPComplexField()
1727
sage: u = MPC(2, 4)
1728
sage: arcsin(u)
1729
0.453870209963122 + 2.19857302792094*I
1730
"""
1731
cdef MPComplexNumber z
1732
z = self._new()
1733
mpc_asin (z.value, self.value, (<MPComplexField_class>self._parent).__rnd)
1734
return z
1735
1736
def arctan(self):
1737
"""
1738
Return the arctangent of this complex number.
1739
1740
EXAMPLES::
1741
1742
sage: MPC = MPComplexField()
1743
sage: u = MPC(-2, 4)
1744
sage: arctan(u)
1745
-1.46704821357730 + 0.200586618131234*I
1746
"""
1747
cdef MPComplexNumber z
1748
z = self._new()
1749
mpc_atan (z.value, self.value, (<MPComplexField_class>self._parent).__rnd)
1750
return z
1751
1752
def arccosh(self):
1753
"""
1754
Return the hyperbolic arccos of this complex number.
1755
1756
EXAMPLES::
1757
1758
sage: MPC = MPComplexField()
1759
sage: u = MPC(2, 4)
1760
sage: arccosh(u)
1761
2.19857302792094 + 1.11692611683177*I
1762
"""
1763
cdef MPComplexNumber z
1764
z = self._new()
1765
mpc_acosh (z.value, self.value, (<MPComplexField_class>self._parent).__rnd)
1766
return z
1767
1768
def arcsinh(self):
1769
"""
1770
Return the hyperbolic arcsine of this complex number.
1771
1772
EXAMPLES::
1773
1774
sage: MPC = MPComplexField()
1775
sage: u = MPC(2, 4)
1776
sage: arcsinh(u)
1777
2.18358521656456 + 1.09692154883014*I
1778
"""
1779
cdef MPComplexNumber z
1780
z = self._new()
1781
mpc_asinh (z.value, self.value, (<MPComplexField_class>self._parent).__rnd)
1782
return z
1783
1784
def arctanh(self):
1785
"""
1786
Return the hyperbolic arctangent of this complex number.
1787
1788
EXAMPLES::
1789
1790
sage: MPC = MPComplexField()
1791
sage: u = MPC(2, 4)
1792
sage: arctanh(u)
1793
0.0964156202029962 + 1.37153510396169*I
1794
"""
1795
cdef MPComplexNumber z
1796
z = self._new()
1797
mpc_atanh (z.value, self.value, (<MPComplexField_class>self._parent).__rnd)
1798
return z
1799
1800
def coth(self):
1801
"""
1802
Return the hyperbolic cotangent of this complex number.
1803
1804
EXAMPLES::
1805
1806
sage: MPC = MPComplexField(100)
1807
sage: MPC(1,1).coth()
1808
0.86801414289592494863584920892 - 0.21762156185440268136513424361*I
1809
"""
1810
return ~(self.tanh())
1811
1812
def arccoth(self):
1813
"""
1814
Return the hyperbolic arccotangent of this complex number.
1815
1816
EXAMPLES::
1817
1818
sage: MPC = MPComplexField(100)
1819
sage: MPC(1,1).arccoth()
1820
0.40235947810852509365018983331 - 0.55357435889704525150853273009*I
1821
"""
1822
return (~self).arctanh()
1823
1824
def csc(self):
1825
"""
1826
Return the cosecent of this complex number.
1827
1828
EXAMPLES::
1829
1830
sage: MPC = MPComplexField(100)
1831
sage: MPC(1,1).csc()
1832
0.62151801717042842123490780586 - 0.30393100162842645033448560451*I
1833
"""
1834
return ~(self.sin())
1835
1836
def csch(self):
1837
"""
1838
Return the hyperbolic cosecent of this complex number.
1839
1840
EXAMPLES::
1841
1842
sage: MPC = MPComplexField(100)
1843
sage: MPC(1,1).csch()
1844
0.30393100162842645033448560451 - 0.62151801717042842123490780586*I
1845
"""
1846
return ~(self.sinh())
1847
1848
def arccsch(self):
1849
"""
1850
Return the hyperbolic arcsine of this complex number.
1851
1852
EXAMPLES::
1853
1854
sage: MPC = MPComplexField(100)
1855
sage: MPC(1,1).arccsch()
1856
0.53063753095251782601650945811 - 0.45227844715119068206365839783*I
1857
"""
1858
return (~self).arcsinh()
1859
1860
def sec(self):
1861
"""
1862
Return the secant of this complex number.
1863
1864
EXAMPLES::
1865
1866
sage: MPC = MPComplexField(100)
1867
sage: MPC(1,1).sec()
1868
0.49833703055518678521380589177 + 0.59108384172104504805039169297*I
1869
"""
1870
return ~(self.cos())
1871
1872
def sech(self):
1873
"""
1874
Return the hyperbolic secant of this complex number.
1875
1876
EXAMPLES::
1877
1878
sage: MPC = MPComplexField(100)
1879
sage: MPC(1,1).sech()
1880
0.49833703055518678521380589177 - 0.59108384172104504805039169297*I
1881
"""
1882
return ~(self.cosh())
1883
1884
def arcsech(self):
1885
"""
1886
Return the hyperbolic arcsecant of this complex number.
1887
1888
EXAMPLES::
1889
1890
sage: MPC = MPComplexField(100)
1891
sage: MPC(1,1).arcsech()
1892
0.53063753095251782601650945811 - 1.1185178796437059371676632938*I
1893
"""
1894
return (~self).arccosh()
1895
1896
def cotan(self):
1897
"""
1898
Return the cotangent of this complex number.
1899
1900
EXAMPLES::
1901
1902
sage: MPC = MPComplexField(53)
1903
sage: (1+MPC(I)).cotan()
1904
0.217621561854403 - 0.868014142895925*I
1905
sage: i = MPComplexField(200).0
1906
sage: (1+i).cotan()
1907
0.21762156185440268136513424360523807352075436916785404091068 - 0.86801414289592494863584920891627388827343874994609327121115*I
1908
sage: i = MPComplexField(220).0
1909
sage: (1+i).cotan()
1910
0.21762156185440268136513424360523807352075436916785404091068124239 - 0.86801414289592494863584920891627388827343874994609327121115071646*I
1911
"""
1912
return ~(self.tan())
1913
1914
################################
1915
# Other functions
1916
################################
1917
1918
def argument(self):
1919
r"""
1920
The argument (angle) of the complex number, normalized so that
1921
`-\pi < \theta \leq \pi`.
1922
1923
EXAMPLES::
1924
1925
sage: MPC = MPComplexField()
1926
sage: i = MPC.0
1927
sage: (i^2).argument()
1928
3.14159265358979
1929
sage: (1+i).argument()
1930
0.785398163397448
1931
sage: i.argument()
1932
1.57079632679490
1933
sage: (-i).argument()
1934
-1.57079632679490
1935
sage: (RR('-0.001') - i).argument()
1936
-1.57179632646156
1937
"""
1938
cdef RealNumber x
1939
x = RealNumber(self._parent._real_field())
1940
mpc_arg(x.value, self.value, (<RealField_class>x._parent).rnd)
1941
return x
1942
1943
def conjugate(self):
1944
r"""
1945
Return the complex conjugate of this complex number:
1946
1947
.. MATH::
1948
1949
\mathrm{conjugate}(a + ib) = a - ib.
1950
1951
EXAMPLES::
1952
1953
sage: MPC = MPComplexField()
1954
sage: i = MPC(0, 1)
1955
sage: (1+i).conjugate()
1956
1.00000000000000 - 1.00000000000000*I
1957
"""
1958
cdef MPComplexNumber z
1959
z = self._new()
1960
mpc_conj(z.value, self.value, (<MPComplexField_class>self._parent).__rnd)
1961
return z
1962
1963
def sqr(self):
1964
"""
1965
Return the square of a complex number:
1966
1967
.. MATH::
1968
1969
(a + ib)^2 = (a^2 - b^2) + 2iab.
1970
1971
EXAMPLES::
1972
1973
sage: C = MPComplexField()
1974
sage: a = C(5, 1)
1975
sage: a.sqr()
1976
24.0000000000000 + 10.0000000000000*I
1977
"""
1978
cdef MPComplexNumber z
1979
z = self._new()
1980
mpc_sqr (z.value, self.value, (<MPComplexField_class>self._parent).__rnd)
1981
return z
1982
1983
def sqrt(self):
1984
r"""
1985
Return the square root, taking the branch cut to be the negative real
1986
axis:
1987
1988
.. MATH::
1989
1990
\sqrt z = \sqrt{|z|}(\cos(\arg(z)/2) + i \sin(\arg(z)/2)).
1991
1992
EXAMPLES::
1993
1994
sage: C = MPComplexField()
1995
sage: a = C(24, 10)
1996
sage: a.sqrt()
1997
5.00000000000000 + 1.00000000000000*I
1998
"""
1999
cdef MPComplexNumber z
2000
z = self._new()
2001
mpc_sqrt(z.value, self.value, (<MPComplexField_class>self._parent).__rnd)
2002
return z
2003
2004
def exp(self):
2005
"""
2006
Return the exponential of this complex number:
2007
2008
.. MATH::
2009
2010
\exp(a + ib) = \exp(a) (\cos b + i \sin b).
2011
2012
EXAMPLES::
2013
2014
sage: MPC = MPComplexField()
2015
sage: u = MPC(2, 4)
2016
sage: exp(u)
2017
-4.82980938326939 - 5.59205609364098*I
2018
"""
2019
cdef MPComplexNumber z
2020
z = self._new()
2021
mpc_exp(z.value, self.value, (<MPComplexField_class>self._parent).__rnd)
2022
return z
2023
2024
def log(self):
2025
r"""
2026
Return the logarithm of this complex number with the branch
2027
cut on the negative real axis:
2028
2029
.. MATH::
2030
2031
\log(z) = \log |z| + i \arg(z).
2032
2033
EXAMPLES::
2034
2035
sage: MPC = MPComplexField()
2036
sage: u = MPC(2, 4)
2037
sage: log(u)
2038
1.49786613677700 + 1.10714871779409*I
2039
"""
2040
cdef MPComplexNumber z
2041
z = self._new()
2042
mpc_log(z.value, self.value, (<MPComplexField_class>self._parent).__rnd)
2043
return z
2044
2045
def __lshift__(self, n):
2046
"""
2047
Fast multiplication by `2^n`.
2048
2049
EXAMPLES::
2050
2051
sage: MPC = MPComplexField()
2052
sage: u = MPC(2, 4)
2053
sage: u<<2
2054
8.00000000000000 + 16.0000000000000*I
2055
sage: u<<(-1)
2056
1.00000000000000 + 2.00000000000000*I
2057
"""
2058
cdef MPComplexNumber z, x
2059
x = <MPComplexNumber>self
2060
z = x._new()
2061
mpc_mul_2si(z.value , x.value, n, (<MPComplexField_class>x._parent).__rnd)
2062
return z
2063
2064
def __rshift__(self, n):
2065
"""
2066
Fast division by `2^n`.
2067
2068
EXAMPLES::
2069
2070
sage: MPC = MPComplexField()
2071
sage: u = MPC(2, 4)
2072
sage: u>>2
2073
0.500000000000000 + 1.00000000000000*I
2074
sage: u>>(-1)
2075
4.00000000000000 + 8.00000000000000*I
2076
"""
2077
cdef MPComplexNumber z, x
2078
x = <MPComplexNumber>self
2079
z = x._new()
2080
mpc_div_2si(z.value , x.value, n, (<MPComplexField_class>x._parent).__rnd)
2081
return z
2082
2083
def nth_root(self, n, all=False):
2084
"""
2085
The `n`-th root function.
2086
2087
INPUT:
2088
2089
- ``all`` - bool (default: ``False``); if ``True``, return a
2090
list of all `n`-th roots.
2091
2092
EXAMPLES::
2093
2094
sage: MPC = MPComplexField()
2095
sage: a = MPC(27)
2096
sage: a.nth_root(3)
2097
3.00000000000000
2098
sage: a.nth_root(3, all=True)
2099
[3.00000000000000, -1.50000000000000 + 2.59807621135332*I, -1.50000000000000 - 2.59807621135332*I]
2100
"""
2101
if self.is_zero():
2102
return [self] if all else self
2103
2104
cdef RealField_class R = self._parent._real_field()
2105
cdef mpfr_rnd_t rrnd = R.rnd
2106
cdef mpc_rnd_t crnd = (<MPComplexField_class>(self._parent)).__rnd
2107
2108
cdef RealNumber a,r
2109
a = self.argument()/n
2110
r = self.abs()
2111
mpfr_root(r.value, r.value, n, rrnd)
2112
2113
cdef MPComplexNumber z
2114
z = self._new()
2115
mpfr_sin_cos(z.value.im, z.value.re, a.value, rrnd)
2116
mpc_mul_fr(z.value, z.value, r.value, crnd)
2117
2118
if not all:
2119
return z
2120
2121
cdef RealNumber t, tt
2122
t = R.pi()*2/n
2123
tt= RealNumber(R)
2124
2125
cdef list zlist = [z]
2126
for i in xrange(1,n):
2127
z = self._new()
2128
mpfr_mul_ui(tt.value, t.value, i, rrnd)
2129
mpfr_add(tt.value, tt.value, a.value, rrnd)
2130
mpfr_sin_cos(z.value.im, z.value.re, tt.value, rrnd)
2131
mpc_mul_fr(z.value, z.value, r.value, crnd)
2132
zlist.append(z)
2133
2134
return zlist
2135
2136
def dilog(self):
2137
r"""
2138
Return the complex dilogarithm of ``self``.
2139
2140
The complex dilogarithm, or Spence's function, is defined by
2141
2142
.. MATH::
2143
2144
Li_2(z) = - \int_0^z \frac{\log|1-\zeta|}{\zeta} d(\zeta)
2145
= \sum_{k=1}^\infty \frac{z^k}{k^2}.
2146
2147
Note that the series definition can only be used for `|z| < 1`.
2148
2149
EXAMPLES::
2150
2151
sage: MPC = MPComplexField()
2152
sage: a = MPC(1,0)
2153
sage: a.dilog()
2154
1.64493406684823
2155
sage: float(pi^2/6)
2156
1.6449340668482262
2157
2158
::
2159
2160
sage: b = MPC(0,1)
2161
sage: b.dilog()
2162
-0.205616758356028 + 0.915965594177219*I
2163
2164
::
2165
2166
sage: c = MPC(0,0)
2167
sage: c.dilog()
2168
0
2169
"""
2170
return self._parent(self._pari_().dilog())
2171
2172
def eta(self, omit_frac=False):
2173
r"""
2174
Return the value of the Dedekind `\eta` function on ``self``,
2175
intelligently computed using `\mathbb{SL}(2,\ZZ)` transformations.
2176
2177
The `\eta` function is
2178
2179
.. MATH::
2180
2181
\eta(z) = e^{\pi i z / 12} \prod_{n=1}^{\infty}(1-e^{2\pi inz})
2182
2183
INPUT:
2184
2185
- ``self`` - element of the upper half plane (if not,
2186
raises a ``ValueError``).
2187
2188
- ``omit_frac`` - (bool, default: ``False``), if ``True``,
2189
omit the `e^{\pi i z / 12}` factor.
2190
2191
OUTPUT: a complex number
2192
2193
ALGORITHM: Uses the PARI C library.
2194
2195
EXAMPLES::
2196
2197
sage: MPC = MPComplexField()
2198
sage: i = MPC.0
2199
sage: z = 1+i; z.eta()
2200
0.742048775836565 + 0.198831370229911*I
2201
"""
2202
try:
2203
return self._parent(self._pari_().eta(not omit_frac))
2204
except sage.libs.pari.all.PariError:
2205
raise ValueError, "value must be in the upper half plane"
2206
2207
def gamma(self):
2208
"""
2209
Return the Gamma function evaluated at this complex number.
2210
2211
EXAMPLES::
2212
2213
sage: MPC = MPComplexField(30)
2214
sage: i = MPC.0
2215
sage: (1+i).gamma()
2216
0.49801567 - 0.15494983*I
2217
2218
TESTS::
2219
2220
sage: MPC(0).gamma()
2221
Infinity
2222
2223
::
2224
2225
sage: MPC(-1).gamma()
2226
Infinity
2227
"""
2228
try:
2229
return self._parent(self._pari_().gamma())
2230
except sage.libs.pari.all.PariError:
2231
from sage.rings.infinity import UnsignedInfinityRing
2232
return UnsignedInfinityRing.gen()
2233
2234
def gamma_inc(self, t):
2235
"""
2236
Return the incomplete Gamma function evaluated at this complex number.
2237
2238
EXAMPLES::
2239
2240
sage: C, i = MPComplexField(30).objgen()
2241
sage: (1+i).gamma_inc(2 + 3*i)
2242
0.0020969149 - 0.059981914*I
2243
sage: (1+i).gamma_inc(5)
2244
-0.0013781309 + 0.0065198200*I
2245
sage: C(2).gamma_inc(1 + i)
2246
0.70709210 - 0.42035364*I
2247
2248
"""
2249
return self._parent(self._pari_().incgam(t))
2250
2251
def zeta(self):
2252
"""
2253
Return the Riemann zeta function evaluated at this complex number.
2254
2255
EXAMPLES::
2256
2257
sage: i = MPComplexField(30).gen()
2258
sage: z = 1 + i
2259
sage: z.zeta()
2260
0.58215806 - 0.92684856*I
2261
"""
2262
return self._parent(self._pari_().zeta())
2263
2264
def agm(self, right, algorithm="optimal"):
2265
"""
2266
Returns the algebraic geometrc mean of ``self`` and ``right``.
2267
2268
EXAMPLES::
2269
2270
sage: MPC = MPComplexField()
2271
sage: u = MPC(1, 4)
2272
sage: v = MPC(-2,5)
2273
sage: u.agm(v, algorithm="pari")
2274
-0.410522769709397 + 4.60061063922097*I
2275
sage: u.agm(v, algorithm="principal")
2276
1.24010691168158 - 0.472193567796433*I
2277
sage: u.agm(v, algorithm="optimal")
2278
-0.410522769709397 + 4.60061063922097*I
2279
"""
2280
if algorithm=="pari":
2281
t = self._parent(right)._pari_()
2282
return self._parent(self._pari_().agm(t))
2283
2284
cdef MPComplexNumber a, b, d, s, res
2285
cdef mpfr_t sn,dn
2286
cdef mp_exp_t rel_prec
2287
cdef bint optimal = algorithm == "optimal"
2288
2289
cdef mpc_rnd_t rnd = (<MPComplexField_class>(self._parent)).__rnd
2290
2291
cdef int prec = self._parent.__prec
2292
2293
if optimal or algorithm == "principal":
2294
if not isinstance(right, MPComplexNumber) or (<MPComplexNumber>right)._parent is not self._parent:
2295
right = self._parent(right)
2296
2297
res = self._new()
2298
2299
if self.is_zero():
2300
return self
2301
elif (<MPComplexNumber>right).is_zero():
2302
return right
2303
elif (mpfr_cmpabs(self.value.re, (<MPComplexNumber>right).value.re) == 0 and
2304
mpfr_cmpabs(self.value.im, (<MPComplexNumber>right).value.im) == 0 and
2305
mpfr_cmp(self.value.re, (<MPComplexNumber>right).value.re) != 0 and
2306
mpfr_cmp(self.value.im, (<MPComplexNumber>right).value.im) != 0):
2307
# self = -right
2308
mpc_set_ui(res.value, 0, rnd)
2309
return res
2310
# Do the computations to a bit higher precicion so rounding error
2311
# won't obscure the termination condition.
2312
a = MPComplexNumber(MPComplexField(prec+5), None)
2313
b = a._new()
2314
d = a._new()
2315
s = a._new()
2316
2317
# Make copies so we don't mutate self or right.
2318
mpc_set(a.value, self.value, rnd)
2319
mpc_set(b.value, (<MPComplexNumber>right).value, rnd)
2320
2321
if optimal:
2322
mpc_add(s.value, a.value, b.value, rnd)
2323
2324
while True:
2325
# s = a+b
2326
if not optimal:
2327
mpc_add(s.value, a.value, b.value, rnd)
2328
2329
# b = sqrt(a*b)
2330
mpc_mul(d.value, a.value, b.value, rnd)
2331
mpc_sqrt(b.value, d.value, rnd)
2332
2333
# a = s/2
2334
mpc_div_2ui(a.value, s.value, 1, rnd)
2335
2336
# d = a - b
2337
mpc_sub(d.value, a.value, b.value, rnd)
2338
if d.is_zero():
2339
mpc_set(res.value, a.value, rnd)
2340
return res
2341
2342
if optimal:
2343
# s = a+b
2344
mpc_add(s.value, a.value, b.value, rnd)
2345
if s.is_zero():
2346
mpc_set(res.value, a.value, rnd)
2347
return res
2348
2349
# |s| < |d|
2350
if s.norm() < d.norm():
2351
mpc_swap(d.value, s.value)
2352
mpc_neg(b.value, b.value, rnd)
2353
2354
rel_prec = min_exp_t(max_exp(a), max_exp(b)) - max_exp(d)
2355
if rel_prec > prec:
2356
mpc_set(res.value, a.value, rnd)
2357
return res
2358
2359
cdef inline mp_exp_t min_exp_t(mp_exp_t a, mp_exp_t b):
2360
return a if a < b else b
2361
cdef inline mp_exp_t max_exp_t(mp_exp_t a, mp_exp_t b):
2362
return a if a > b else b
2363
2364
cdef inline mp_exp_t max_exp(MPComplexNumber z):
2365
"""
2366
Quickly return the maximum exponent of the real and complex parts of ``z``,
2367
which is useful for estimating its magnitude.
2368
"""
2369
if mpfr_zero_p(z.value.im):
2370
return mpfr_get_exp(z.value.re)
2371
elif mpfr_zero_p(z.value.re):
2372
return mpfr_get_exp(z.value.im)
2373
return max_exp_t(mpfr_get_exp(z.value.re), mpfr_get_exp(z.value.im))
2374
2375
def __create__MPComplexField_version0 (prec, rnd):
2376
"""
2377
Create a :class:`MPComplexField`.
2378
2379
EXAMPLES::
2380
2381
sage: sage.rings.complex_mpc.__create__MPComplexField_version0(200, 'RNDDZ')
2382
Complex Field with 200 bits of precision and rounding RNDDZ
2383
"""
2384
return MPComplexField(prec, rnd)
2385
2386
def __create__MPComplexNumber_version0 (parent, s, base=10):
2387
"""
2388
Create a :class:`MPComplexNumber`.
2389
2390
EXAMPLES::
2391
2392
sage: C = MPComplexField(prec=20, rnd='RNDUU')
2393
sage: sage.rings.complex_mpc.__create__MPComplexNumber_version0(C, 3.2+2*i)
2394
3.2001 + 2.0000*I
2395
"""
2396
return MPComplexNumber(parent, s, base=base)
2397
2398
# original version of the file had this with only 1 underscore - TCS
2399
__create_MPComplexNumber_version0 = __create__MPComplexNumber_version0
2400
2401
#*****************************************************************************
2402
#
2403
# Morphisms
2404
#
2405
#*****************************************************************************
2406
2407
cdef class MPCtoMPC(Map):
2408
cpdef Element _call_(self, z):
2409
"""
2410
EXAMPLES::
2411
2412
sage: from sage.rings.complex_mpc import *
2413
sage: C10 = MPComplexField(10)
2414
sage: C100 = MPComplexField(100)
2415
sage: f = MPCtoMPC(C100, C10) # indirect doctest
2416
sage: a = C100(1.2, 24)
2417
sage: f(a)
2418
1.2 + 24.*I
2419
sage: f
2420
Generic map:
2421
From: Complex Field with 100 bits of precision
2422
To: Complex Field with 10 bits of precision
2423
"""
2424
cdef MPComplexNumber y
2425
y = (<MPComplexField_class>self._codomain)._new()
2426
y._set(z)
2427
return y
2428
2429
def section(self):
2430
"""
2431
EXAMPLES::
2432
2433
sage: from sage.rings.complex_mpc import *
2434
sage: C10 = MPComplexField(10)
2435
sage: C100 = MPComplexField(100)
2436
sage: f = MPCtoMPC(C100, C10)
2437
sage: f.section()
2438
Generic map:
2439
From: Complex Field with 10 bits of precision
2440
To: Complex Field with 100 bits of precision
2441
"""
2442
return MPCtoMPC(self._codomain, self._domain)
2443
2444
cdef class INTEGERtoMPC(Map):
2445
cpdef Element _call_(self, x):
2446
"""
2447
EXAMPLES::
2448
2449
sage: from sage.rings.complex_mpc import *
2450
sage: I = IntegerRing()
2451
sage: C100 = MPComplexField(100)
2452
sage: f = MPFRtoMPC(I, C100); f # indirect doctest
2453
Generic map:
2454
From: Integer Ring
2455
To: Complex Field with 100 bits of precision
2456
sage: a = I(625)
2457
sage: f(a)
2458
625.00000000000000000000000000
2459
"""
2460
cdef MPComplexNumber y
2461
cdef mpc_rnd_t rnd
2462
rnd =(<MPComplexField_class>self._parent).__rnd
2463
y = (<MPComplexField_class>self._codomain)._new()
2464
mpc_set_z(y.value, (<Integer>x).value, rnd)
2465
return y
2466
2467
cdef class MPFRtoMPC(Map):
2468
cpdef Element _call_(self, x):
2469
"""
2470
EXAMPLES::
2471
2472
sage: from sage.rings.complex_mpc import *
2473
sage: R10 = RealField(10)
2474
sage: C100 = MPComplexField(100)
2475
sage: f = MPFRtoMPC(R10, C100); f # indirect doctest
2476
Generic map:
2477
From: Real Field with 10 bits of precision
2478
To: Complex Field with 100 bits of precision
2479
sage: a = R10(1.625)
2480
sage: f(a)
2481
1.6250000000000000000000000000
2482
"""
2483
cdef MPComplexNumber y
2484
# cdef mpc_rnd_t rnd
2485
# rnd =(<MPComplexField_class>self._parent).__rnd
2486
y = (<MPComplexField_class>self._codomain)._new()
2487
# mpc_set_fr(y.value, (<RealNumber>x).value, rnd)
2488
y._set(x)
2489
return y
2490
2491
cdef class CCtoMPC(Map):
2492
cpdef Element _call_(self, z):
2493
"""
2494
EXAMPLES::
2495
2496
sage: from sage.rings.complex_mpc import *
2497
sage: C10 = ComplexField(10)
2498
sage: MPC100 = MPComplexField(100)
2499
sage: f = CCtoMPC(C10, MPC100); f # indirect doctest
2500
Generic map:
2501
From: Complex Field with 10 bits of precision
2502
To: Complex Field with 100 bits of precision
2503
sage: a = C10(1.625, 42)
2504
sage: f(a)
2505
1.6250000000000000000000000000 + 42.000000000000000000000000000*I
2506
"""
2507
cdef MPComplexNumber y
2508
cdef mpc_rnd_t rnd
2509
rnd =(<MPComplexField_class>self._parent).__rnd
2510
y = (<MPComplexField_class>self._codomain)._new()
2511
mpc_set_fr_fr(y.value, (<ComplexNumber>z).__re, (<ComplexNumber>z).__im, rnd)
2512
return y
2513
2514
2515