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