Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagelib
Path: blob/master/sage/rings/complex_double.pyx
4048 views
1
r"""
2
Double Precision Complex Numbers
3
4
Sage supports arithmetic using double-precision complex numbers. A
5
double-precision complex number is a complex number x + I\*y with
6
x, y 64-bit (8 byte) floating point numbers (double precision).
7
8
The field ``ComplexDoubleField`` implements the field
9
of all double-precision complex numbers. You can refer to this
10
field by the shorthand CDF. Elements of this field are of type
11
``ComplexDoubleElement``. If x and y are coercible to
12
doubles, you can create a complex double element using
13
``ComplexDoubleElement(x,y)``. You can coerce more
14
general objects z to complex doubles by typing either
15
``ComplexDoubleField(x)`` or ``CDF(x)``.
16
17
EXAMPLES::
18
19
sage: ComplexDoubleField()
20
Complex Double Field
21
sage: CDF
22
Complex Double Field
23
sage: type(CDF.0)
24
<type 'sage.rings.complex_double.ComplexDoubleElement'>
25
sage: ComplexDoubleElement(sqrt(2),3)
26
1.41421356237 + 3.0*I
27
sage: parent(CDF(-2))
28
Complex Double Field
29
30
::
31
32
sage: CC == CDF
33
False
34
sage: CDF is ComplexDoubleField() # CDF is the shorthand
35
True
36
sage: CDF == ComplexDoubleField()
37
True
38
39
The underlying arithmetic of complex numbers is implemented using
40
functions and macros in GSL (the GNU Scientific Library), and
41
should be very fast. Also, all standard complex trig functions,
42
log, exponents, etc., are implemented using GSL, and are also
43
robust and fast. Several other special functions, e.g. eta, gamma,
44
incomplete gamma, etc., are implemented using the PARI C library.
45
46
AUTHORS:
47
48
- William Stein (2006-09): first version
49
"""
50
51
#################################################################################
52
# Copyright (C) 2006 William Stein <[email protected]>
53
#
54
# Distributed under the terms of the GNU General Public License (GPL)
55
#
56
# http://www.gnu.org/licenses/
57
#*****************************************************************************
58
59
import operator
60
61
from sage.misc.randstate cimport randstate, current_randstate
62
63
include '../ext/interrupt.pxi'
64
include '../ext/stdsage.pxi'
65
66
cdef extern from "math.h":
67
double modf (double value, double *integer_part)
68
69
# The M_PI_4 constant is not available on cygwin in "math.h" (though
70
# it is on most other platforms).
71
cdef double M_PI_4 = 0.785398163397448309615660845819875721
72
73
cdef extern from "complex.h":
74
double complex csqrt(double complex)
75
double cabs(double complex)
76
77
cimport sage.rings.ring
78
79
cimport sage.rings.integer
80
81
from sage.structure.element cimport RingElement, Element, ModuleElement, FieldElement
82
from sage.structure.parent cimport Parent
83
84
cimport sage.libs.pari.gen
85
import sage.libs.pari.gen
86
87
88
import complex_number
89
90
cdef RR, CC, RDF
91
import complex_field
92
CC = complex_field.ComplexField()
93
94
import real_mpfr
95
RR = real_mpfr.RealField()
96
97
from real_double import RealDoubleElement, RDF
98
99
# PREC is the precision (in decimal digits) that all PARI computations with doubles
100
# are done with in this module. A double is by definition 8 bytes or 64 bits. Since
101
# log(2^64,10) = 19.265919722494793 < 28
102
# 28 *digits* should be way more than enough for correctness to 64 bits. We choose
103
# 28 since 20 gets rounded up to 28 digits automatically by PARI anyways. In theory
104
# 19 digits might also be OK, but I've noticed that last digit or two of PARI output
105
# can be questionable -- it varies from version to version, so...
106
cdef int PREC
107
PREC = 28
108
109
from sage.structure.parent_gens import ParentWithGens
110
from sage.categories.morphism cimport Morphism
111
112
def is_ComplexDoubleField(x):
113
"""
114
Return True if x is the complex double field.
115
116
EXAMPLE::
117
118
sage: from sage.rings.complex_double import is_ComplexDoubleField
119
sage: is_ComplexDoubleField(CDF)
120
True
121
sage: is_ComplexDoubleField(ComplexField(53))
122
False
123
"""
124
return PY_TYPE_CHECK(x, ComplexDoubleField_class)
125
126
cdef class ComplexDoubleField_class(sage.rings.ring.Field):
127
"""
128
An approximation to the field of complex numbers using double
129
precision floating point numbers. Answers derived from calculations
130
in this approximation may differ from what they would be if those
131
calculations were performed in the true field of complex numbers.
132
This is due to the rounding errors inherent to finite precision
133
calculations.
134
135
ALGORITHMS: Arithmetic is done using GSL (the GNU Scientific
136
Library).
137
"""
138
def __init__(self):
139
"""
140
Construct field of complex double precision numbers.
141
142
EXAMPLE::
143
144
sage: from sage.rings.complex_double import ComplexDoubleField_class
145
sage: CDF == ComplexDoubleField_class()
146
True
147
sage: TestSuite(CDF).run(skip = ["_test_prod"])
148
149
.. warning:: due to rounding errors, one can have `x^2 != x*x`::
150
151
sage: x = CDF.an_element()
152
sage: x
153
1.0*I
154
sage: x*x, x**2, x*x == x**2
155
(-1.0, -1.0 + 1.2246...e-16*I, False)
156
"""
157
from sage.categories.fields import Fields
158
ParentWithGens.__init__(self, self, ('I',), normalize=False, category = Fields())
159
self._populate_coercion_lists_()
160
161
def __reduce__(self):
162
"""
163
::
164
165
sage: loads(dumps(CDF)) is CDF
166
True
167
"""
168
return ComplexDoubleField, ()
169
170
cpdef bint is_exact(self) except -2:
171
"""
172
Returns whether or not this field is exact, which is always false.
173
174
EXAMPLE::
175
176
sage: CDF.is_exact()
177
False
178
"""
179
return False
180
181
def __richcmp__(left, right, int op):
182
return (<Parent>left)._richcmp_helper(right, op)
183
184
cdef int _cmp_c_impl(left, Parent right) except -2:
185
# There is only one CDF.
186
return cmp(type(left),type(right))
187
188
def __hash__(self):
189
"""
190
TEST::
191
192
sage: hash(CDF) % 2^32 == hash(str(CDF)) % 2^32
193
True
194
"""
195
return 561162115
196
#return hash(self.str())
197
198
def characteristic(self):
199
"""
200
Return the characteristic of this complex double field, which is
201
0.
202
203
EXAMPLES::
204
205
sage: CDF.characteristic()
206
0
207
"""
208
import integer
209
return integer.Integer(0)
210
211
def random_element(self, double xmin=-1, double xmax=1, double ymin=-1, double ymax=1):
212
"""
213
Return a random element of this complex double field with real and
214
imaginary part bounded by xmin, xmax, ymin, ymax.
215
216
EXAMPLES::
217
218
sage: CDF.random_element()
219
-0.436810529675 + 0.736945423566*I
220
sage: CDF.random_element(-10,10,-10,10)
221
-7.08874026302 - 9.54135400334*I
222
sage: CDF.random_element(-10^20,10^20,-2,2)
223
-7.58765473764e+19 + 0.925549022839*I
224
"""
225
cdef randstate rstate = current_randstate()
226
global _CDF
227
cdef ComplexDoubleElement z
228
cdef double imag = (ymax-ymin)*rstate.c_rand_double() + ymin
229
cdef double real = (xmax-xmin)*rstate.c_rand_double() + xmin
230
z = PY_NEW(ComplexDoubleElement)
231
z._complex = gsl_complex_rect(real, imag)
232
return z
233
234
def _repr_(self):
235
"""
236
Print out this complex double field.
237
238
EXAMPLES::
239
240
sage: ComplexDoubleField()
241
Complex Double Field
242
sage: CDF
243
Complex Double Field
244
"""
245
return "Complex Double Field"
246
247
def _latex_(self):
248
r"""
249
Return a LaTeX representation of ``self``.
250
251
OUTPUT:
252
253
- a string.
254
255
TESTS::
256
257
sage: print CDF._latex_()
258
\Bold{C}
259
"""
260
return r"\Bold{C}"
261
262
def _cmp_(self, x):
263
"""
264
EXAMPLES::
265
266
sage: CDF == 5
267
False
268
sage: loads(dumps(CDF)) == CDF
269
True
270
"""
271
if PY_TYPE_CHECK(x, ComplexDoubleField_class):
272
return 0
273
return cmp(type(self), type(x))
274
275
def __call__(self, x, im=None):
276
"""
277
Create a complex double using x and optionally an imaginary part
278
im.
279
280
EXAMPLES::
281
282
sage: CDF(0,1)
283
1.0*I
284
sage: CDF(2/3)
285
0.666666666667
286
sage: CDF(5)
287
5.0
288
sage: CDF('i')
289
1.0*I
290
sage: CDF(complex(2,-3))
291
2.0 - 3.0*I
292
sage: CDF(4.5)
293
4.5
294
sage: CDF(1+I)
295
1.0 + 1.0*I
296
297
A TypeError is raised if the coercion doesn't make sense::
298
299
sage: CDF(QQ['x'].0)
300
Traceback (most recent call last):
301
...
302
TypeError: cannot coerce nonconstant polynomial to float
303
304
One can convert back and forth between double precision complex
305
numbers and higher-precision ones, though of course there may be
306
loss of precision::
307
308
sage: a = ComplexField(200)(-2).sqrt(); a
309
1.4142135623730950488016887242096980785696718753769480731767*I
310
sage: b = CDF(a); b
311
1.41421356237*I
312
sage: a.parent()(b)
313
1.4142135623730951454746218587388284504413604736328125000000*I
314
sage: a.parent()(b) == b
315
True
316
sage: b == CC(a)
317
True
318
"""
319
# We implement __call__ to gracefully accept the second argument.
320
if im is not None:
321
x = x, im
322
return Parent.__call__(self, x)
323
324
def _element_constructor_(self, x):
325
"""
326
See ``__call__``.
327
328
EXAMPLES::
329
330
sage: CDF((1,2))
331
1.0 + 2.0*I
332
"""
333
cdef pari_sp sp
334
if PY_TYPE_CHECK(x, ComplexDoubleElement):
335
return x
336
elif PY_TYPE_CHECK(x, tuple):
337
return ComplexDoubleElement(x[0], x[1])
338
elif isinstance(x, (float, int, long)):
339
return ComplexDoubleElement(x, 0)
340
elif isinstance(x, complex):
341
return ComplexDoubleElement(x.real, x.imag)
342
elif isinstance(x, complex_number.ComplexNumber):
343
return ComplexDoubleElement(x.real(), x.imag())
344
elif isinstance(x, sage.libs.pari.gen.gen):
345
# It seems we should get a speed increase by
346
# using _new_from_gen_c instead; I wasn't
347
# able to get this to work.
348
return ComplexDoubleElement(x.real(), x.imag())
349
elif isinstance(x, str):
350
t = cdf_parser.parse_expression(x)
351
if isinstance(t, float):
352
return ComplexDoubleElement(t, 0)
353
else:
354
return t
355
elif hasattr(x, '_complex_double_'):
356
return x._complex_double_(self)
357
else:
358
return ComplexDoubleElement(x, 0)
359
360
cpdef _coerce_map_from_(self, S):
361
"""
362
Return the canonical coerce of x into the complex double field, if
363
it is defined, otherwise raise a TypeError.
364
365
The rings that canonically coerce to the complex double field are:
366
367
- the complex double field itself
368
369
- anything that canonically coerces to real double field.
370
371
- mathematical constants
372
373
- the 53-bit mpfr complex field
374
375
EXAMPLES::
376
377
sage: CDF._coerce_(5)
378
5.0
379
sage: CDF._coerce_(RDF(3.4))
380
3.4
381
382
Thus the sum of a CDF and a symbolic object is symbolic::
383
384
sage: a = pi + CDF.0; a
385
pi + 1.0*I
386
sage: parent(a)
387
Symbolic Ring
388
389
TESTS::
390
391
sage: CDF(1) + RR(1)
392
2.0
393
sage: CDF.0 - CC(1) - long(1) - RR(1) - QQbar(1)
394
-4.0 + 1.0*I
395
sage: CDF.has_coerce_map_from(ComplexField(20))
396
False
397
"""
398
from integer_ring import ZZ
399
from rational_field import QQ
400
from real_lazy import RLF
401
from real_mpfr import RR, RealField_class
402
from complex_field import ComplexField, ComplexField_class
403
CC = ComplexField()
404
from complex_number import CCtoCDF
405
if S in [int, float, ZZ, QQ, RDF, RLF] or isinstance(S, RealField_class) and S.prec() >= 53:
406
return FloatToCDF(S)
407
elif RR.has_coerce_map_from(S):
408
return FloatToCDF(RR) * RR.coerce_map_from(S)
409
elif isinstance(S, ComplexField_class) and S.prec() >= 53:
410
return CCtoCDF(S, self)
411
elif CC.has_coerce_map_from(S):
412
return CCtoCDF(CC, self) * CC.coerce_map_from(S)
413
414
def _magma_init_(self, magma):
415
r"""
416
Return a string representation of self in the Magma language.
417
418
EXAMPLES::
419
420
sage: magma(CDF) # optional - magma
421
Complex field of precision 15
422
sage: floor(RR(log(2**53, 10)))
423
15
424
sage: magma(CDF).sage() # optional - magma
425
Complex Field with 53 bits of precision
426
"""
427
return "ComplexField(%s : Bits := true)" % self.prec()
428
429
def prec(self):
430
"""
431
Return the precision of this complex double field (to be more
432
similar to ComplexField). Always returns 53.
433
434
EXAMPLES::
435
436
sage: CDF.prec()
437
53
438
"""
439
return 53
440
441
def to_prec(self, prec):
442
"""
443
Returns the complex field to the specified precision. As doubles
444
have fixed precision, this will only return a complex double field
445
if prec is exactly 53.
446
447
EXAMPLES::
448
449
sage: CDF.to_prec(53)
450
Complex Double Field
451
sage: CDF.to_prec(250)
452
Complex Field with 250 bits of precision
453
"""
454
if prec == 53:
455
return self
456
else:
457
from complex_field import ComplexField
458
return ComplexField(prec)
459
460
461
def gen(self, n=0):
462
"""
463
Return the generator of the complex double field.
464
465
EXAMPLES::
466
467
sage: CDF.0
468
1.0*I
469
sage: CDF.gens()
470
(1.0*I,)
471
"""
472
if n != 0:
473
raise ValueError, "only 1 generator"
474
return I
475
476
def ngens(self):
477
"""
478
The number of generators of this complex field as an RR-algebra.
479
480
There is one generator, namely sqrt(-1).
481
482
EXAMPLES::
483
484
sage: CDF.ngens()
485
1
486
"""
487
return 1
488
489
def algebraic_closure(self):
490
r"""
491
Returns the algebraic closure of self, i.e., the complex double
492
field.
493
494
EXAMPLES::
495
496
sage: CDF.algebraic_closure()
497
Complex Double Field
498
"""
499
return self
500
501
def real_double_field(self):
502
"""
503
The real double field, which you may view as a subfield of this
504
complex double field.
505
506
EXAMPLES::
507
508
sage: CDF.real_double_field()
509
Real Double Field
510
"""
511
import real_double
512
return real_double.RDF
513
514
def pi(self):
515
"""
516
Returns pi as a double precision complex number.
517
518
EXAMPLES::
519
520
sage: CDF.pi()
521
3.14159265359
522
"""
523
return self(3.1415926535897932384626433832)
524
525
def construction(self):
526
"""
527
Returns the functorial construction of self, namely, algebraic
528
closure of the real double field.
529
530
EXAMPLES::
531
532
sage: c, S = CDF.construction(); S
533
Real Double Field
534
sage: CDF == c(S)
535
True
536
"""
537
from sage.categories.pushout import AlgebraicClosureFunctor
538
return (AlgebraicClosureFunctor(), self.real_double_field())
539
540
def zeta(self, n=2):
541
"""
542
Return a primitive `n`-th root of unity in this CDF, for
543
`n\ge1`.
544
545
INPUT:
546
547
548
- ``n`` - a positive integer (default: 2)
549
550
551
OUTPUT: a complex n-th root of unity.
552
553
EXAMPLES::
554
555
sage: CDF.zeta(7)
556
0.623489801859 + 0.781831482468*I
557
sage: CDF.zeta(1)
558
1.0
559
sage: CDF.zeta()
560
-1.0
561
sage: CDF.zeta() == CDF.zeta(2)
562
True
563
564
::
565
566
sage: CDF.zeta(0.5)
567
Traceback (most recent call last):
568
...
569
ValueError: n must be a positive integer
570
sage: CDF.zeta(0)
571
Traceback (most recent call last):
572
...
573
ValueError: n must be a positive integer
574
sage: CDF.zeta(-1)
575
Traceback (most recent call last):
576
...
577
ValueError: n must be a positive integer
578
"""
579
from integer import Integer
580
try:
581
n = Integer(n)
582
except:
583
raise ValueError, "n must be a positive integer"
584
585
if n<1:
586
raise ValueError, "n must be a positive integer"
587
588
if n == 1:
589
x = self(1)
590
elif n == 2:
591
x = self(-1)
592
elif n >= 3:
593
# Use De Moivre
594
# e^(2*pi*i/n) = cos(2pi/n) + i *sin(2pi/n)
595
pi = RDF.pi()
596
z = 2*pi/n
597
x = CDF(z.cos(), z.sin())
598
# x._set_multiplicative_order( n ) # not implemented for CDF
599
return x
600
601
602
cdef public api ComplexDoubleElement new_ComplexDoubleElement():
603
"""
604
Creates a new (empty) ComplexDoubleElement.
605
"""
606
cdef ComplexDoubleElement z
607
z = PY_NEW(ComplexDoubleElement)
608
return z
609
610
def is_ComplexDoubleElement(x):
611
"""
612
Return True if x is a is_ComplexDoubleElement.
613
614
EXAMPLES::
615
616
sage: from sage.rings.complex_double import is_ComplexDoubleElement
617
sage: is_ComplexDoubleElement(0)
618
False
619
sage: is_ComplexDoubleElement(CDF(0))
620
True
621
"""
622
return PY_TYPE_CHECK(x, ComplexDoubleElement)
623
624
cdef class ComplexDoubleElement(FieldElement):
625
"""
626
An approximation to a complex number using double precision
627
floating point numbers. Answers derived from calculations with such
628
approximations may differ from what they would be if those
629
calculations were performed with true complex numbers. This is due
630
to the rounding errors inherent to finite precision calculations.
631
"""
632
633
__array_interface__ = {'typestr': '=c16'}
634
635
def __cinit__(self):
636
self._parent = _CDF
637
638
def __init__(self, real, imag):
639
"""
640
Constructs an element of a complex double field with specified real
641
and imaginary values.
642
643
EXAMPLE::
644
645
sage: ComplexDoubleElement(1,-2)
646
1.0 - 2.0*I
647
"""
648
self._complex = gsl_complex_rect(real, imag)
649
650
def __reduce__(self):
651
"""
652
EXAMPLES::
653
654
sage: a = CDF(-2.7, -3)
655
sage: loads(dumps(a)) == a
656
True
657
"""
658
return (ComplexDoubleElement,
659
(self._complex.dat[0], self._complex.dat[1]))
660
661
cdef ComplexDoubleElement _new_c(self, gsl_complex x):
662
"""
663
C-level code for creating a ComplexDoubleElement from a
664
gsl_complex.
665
"""
666
cdef ComplexDoubleElement z = <ComplexDoubleElement>PY_NEW(ComplexDoubleElement)
667
z._complex = x
668
return z
669
670
cdef _new_from_gen_c(self, GEN g, pari_sp sp):
671
"""
672
C-level code for creating a ComplexDoubleElement from a PARI gen.
673
674
INPUT:
675
676
677
- ``g`` - GEN
678
679
- ``sp`` - stack pointer; if nonzero resets avma to
680
sp.
681
"""
682
cdef gsl_complex x
683
sig_on()
684
# Signal handling is important, since rtodbl can easily overflow
685
x = gsl_complex_rect( rtodbl(greal(g)), rtodbl(gimag(g)) )
686
sig_off()
687
z = self._new_c(x)
688
if sp:
689
avma = sp
690
return z
691
692
def __hash__(self):
693
"""
694
Returns the hash of self, which coincides with the python float and
695
complex (and often int) types for self.
696
697
EXAMPLE::
698
699
sage: hash(CDF(1.2)) == hash(1.2r)
700
True
701
sage: hash(CDF(-1))
702
-2
703
sage: hash(CDF(1.2, 1.3)) == hash(complex(1.2r, 1.3r))
704
True
705
"""
706
return hash(complex(self))
707
708
def __richcmp__(left, right, int op):
709
return (<Element>left)._richcmp(right, op)
710
cdef int _cmp_c_impl(left, Element right) except -2:
711
"""
712
We order the complex numbers in dictionary order by real parts then
713
imaginary parts.
714
715
This order, of course, does not respect the field structure, though
716
it agrees with the usual order on the real numbers.
717
718
EXAMPLES::
719
720
sage: CDF(2,3) < CDF(3,1)
721
True
722
sage: CDF(2,3) > CDF(3,1)
723
False
724
sage: CDF(2,-1) < CDF(2,3)
725
True
726
727
It's dictionary order, not absolute value::
728
729
sage: CDF(-1,3) < CDF(-1,-20)
730
False
731
732
Numbers are coerced before comparison.
733
734
::
735
736
sage: CDF(3,5) < 7
737
True
738
sage: 4.3 > CDF(5,1)
739
False
740
"""
741
if left._complex.dat[0] < (<ComplexDoubleElement>right)._complex.dat[0]:
742
return -1
743
if left._complex.dat[0] > (<ComplexDoubleElement>right)._complex.dat[0]:
744
return 1
745
if left._complex.dat[1] < (<ComplexDoubleElement>right)._complex.dat[1]:
746
return -1
747
if left._complex.dat[1] > (<ComplexDoubleElement>right)._complex.dat[1]:
748
return 1
749
return 0
750
751
def __getitem__(self, n):
752
"""
753
Returns the real or imaginary part of self.
754
755
INPUT:
756
757
758
- ``n`` - integer (either 0 or 1)
759
760
761
Raises an IndexError if n 0 or n 1.
762
763
EXAMPLES::
764
765
sage: P = CDF(2,3)
766
sage: P[0]
767
2.0
768
sage: P[1]
769
3.0
770
sage: P[3]
771
Traceback (most recent call last):
772
...
773
IndexError: index n must be 0 or 1
774
"""
775
if n >= 0 and n <= 1:
776
return self._complex.dat[n]
777
raise IndexError, "index n must be 0 or 1"
778
779
def _magma_init_(self, magma):
780
r"""
781
EXAMPLES::
782
783
sage: magma(CDF(1.2, 0.3)) # optional - magma
784
1.20000000000000 + 0.300000000000000*$.1
785
sage: s = magma(CDF(1.2, 0.3)).sage(); s # optional - magma
786
1.20000000000000 + 0.300000000000000*I
787
sage: s.parent() # optional - magma
788
Complex Field with 53 bits of precision
789
"""
790
return "%s![%s, %s]" % (self.parent()._magma_init_(magma), self.real(), self.imag())
791
792
def prec(self):
793
"""
794
Returns the precision of this number (to be more similar to
795
ComplexNumber). Always returns 53.
796
797
EXAMPLES::
798
799
sage: CDF(0).prec()
800
53
801
"""
802
return 53
803
804
#######################################################################
805
# Coercions
806
#######################################################################
807
808
def __int__(self):
809
"""
810
EXAMPLES::
811
812
sage: int(CDF(1,1))
813
Traceback (most recent call last):
814
...
815
TypeError: can't convert complex to int; use int(abs(z))
816
sage: int(abs(CDF(1,1)))
817
1
818
"""
819
raise TypeError, "can't convert complex to int; use int(abs(z))"
820
821
def __long__(self):
822
"""
823
EXAMPLES::
824
825
sage: long(CDF(1,1))
826
Traceback (most recent call last):
827
...
828
TypeError: can't convert complex to long; use long(abs(z))
829
sage: long(abs(CDF(1,1)))
830
1L
831
"""
832
raise TypeError, "can't convert complex to long; use long(abs(z))"
833
834
def __float__(self):
835
"""
836
Method for converting self to type float. Called by the
837
``float`` function. This conversion will throw an error if
838
the number has a nonzero imaginary part.
839
840
EXAMPLES::
841
842
sage: a = CDF(1, 0)
843
sage: float(a)
844
1.0
845
sage: a = CDF(2,1)
846
sage: float(a)
847
Traceback (most recent call last):
848
...
849
TypeError: Unable to convert 2.0 + 1.0*I to float; use abs() or real_part() as desired
850
sage: a.__float__()
851
Traceback (most recent call last):
852
...
853
TypeError: Unable to convert 2.0 + 1.0*I to float; use abs() or real_part() as desired
854
sage: float(abs(CDF(1,1)))
855
1.4142135623730951
856
"""
857
if self._complex.dat[1]==0:
858
return float(self._complex.dat[0])
859
raise TypeError, "Unable to convert %s to float; use abs() or real_part() as desired"%self
860
861
def __complex__(self):
862
"""
863
EXAMPLES::
864
865
sage: a = complex(2303,-3939)
866
sage: CDF(a)
867
2303.0 - 3939.0*I
868
sage: complex(CDF(a))
869
(2303-3939j)
870
"""
871
return complex(self._complex.dat[0], self._complex.dat[1])
872
873
def _interface_init_(self, I=None):
874
"""
875
Returns self formatted as a string, suitable as input to another
876
computer algebra system. (This is the default function used for
877
exporting to other computer algebra systems.)
878
879
EXAMPLES::
880
881
sage: s1 = CDF(exp(I)); s1
882
0.540302305868 + 0.841470984808*I
883
sage: s1._interface_init_()
884
'0.54030230586813977 + 0.84147098480789650*I'
885
sage: s1 == CDF(gp(s1))
886
True
887
"""
888
# Sending to another computer algebra system is slow anyway, right?
889
return CC(self)._interface_init_(I)
890
891
def __repr__(self):
892
"""
893
Return print version of self.
894
895
EXAMPLES::
896
897
sage: a = CDF(2,-3); a
898
2.0 - 3.0*I
899
sage: a^2
900
-5.0 - 12.0*I
901
sage: (1/CDF(0,0)).__repr__()
902
'NaN + NaN*I'
903
sage: CDF(oo,1)
904
+infinity + 1.0*I
905
sage: CDF(1,oo)
906
1.0 + +infinity*I
907
sage: CDF(1,-oo)
908
1.0 - +infinity*I
909
sage: CC(CDF(1,-oo))
910
1.00000000000000 - +infinity*I
911
sage: CDF(oo,oo)
912
+infinity + +infinity*I
913
sage: CC(CDF(oo,oo))
914
+infinity + +infinity*I
915
sage: CDF(0)
916
0.0
917
"""
918
if self._complex.dat[0]:
919
# real part is nonzero
920
s = double_to_str(self._complex.dat[0])
921
else:
922
# real part is zero
923
if self._complex.dat[1]: # imag is nonzero
924
s = ''
925
else:
926
return double_to_str(self._complex.dat[0]) # imag is zero
927
928
cdef double y = self._complex.dat[1]
929
if y:
930
if s != "":
931
if y < 0:
932
s = s+" - "
933
y = -y
934
else:
935
s = s+" + "
936
t = double_to_str(y)
937
s += t + "*I"
938
return s
939
940
def _latex_(self):
941
"""
942
EXAMPLES::
943
944
sage: CDF(1, 2)._latex_()
945
'1.0 + 2.0i'
946
sage: z = CDF(1,2)^100
947
sage: z._latex_()
948
'-6.44316469099 \\times 10^{34} - 6.11324130776 \\times 10^{34}i'
949
"""
950
import re
951
s = str(self).replace('*I', 'i')
952
return re.sub(r"e\+?(-?\d+)", r" \\times 10^{\1}", s)
953
954
cdef GEN _gen(self):
955
cdef GEN y
956
y = cgetg(3, t_COMPLEX) # allocate space for a complex number
957
cdef sage.libs.pari.gen.PariInstance P = sage.libs.pari.gen.pari
958
set_gel(y,1,P.double_to_GEN(self._complex.dat[0]))
959
set_gel(y,2,P.double_to_GEN(self._complex.dat[1]))
960
return y
961
962
def _pari_(self):
963
"""
964
Return PARI version of self.
965
966
EXAMPLES::
967
968
sage: CDF(1,2)._pari_()
969
1.00000000000000 + 2.00000000000000*I
970
sage: pari(CDF(1,2))
971
1.00000000000000 + 2.00000000000000*I
972
"""
973
# The explicit declaration and assignment is necessary in
974
# order to get access to the internal C structure of gen.pari.
975
cdef pari_sp sp
976
global avma
977
sp = avma
978
cdef sage.libs.pari.gen.PariInstance P
979
P = sage.libs.pari.gen.pari
980
x = P.new_gen_noclear(self._gen())
981
avma = sp
982
return x
983
984
#######################################################################
985
# Arithmetic
986
#######################################################################
987
988
cpdef ModuleElement _add_(self, ModuleElement right):
989
"""
990
Add self and right.
991
992
EXAMPLES::
993
994
sage: CDF(2,-3)._add_(CDF(1,-2))
995
3.0 - 5.0*I
996
"""
997
return self._new_c(gsl_complex_add(self._complex,
998
(<ComplexDoubleElement>right)._complex))
999
1000
cpdef ModuleElement _sub_(self, ModuleElement right):
1001
"""
1002
Subtract self and right.
1003
1004
EXAMPLES::
1005
1006
sage: CDF(2,-3)._sub_(CDF(1,-2))
1007
1.0 - 1.0*I
1008
"""
1009
return self._new_c(gsl_complex_sub(self._complex,
1010
(<ComplexDoubleElement>right)._complex))
1011
1012
cpdef RingElement _mul_(self, RingElement right):
1013
"""
1014
Multiply self and right.
1015
1016
EXAMPLES::
1017
1018
sage: CDF(2,-3)._mul_(CDF(1,-2))
1019
-4.0 - 7.0*I
1020
"""
1021
return self._new_c(gsl_complex_mul(self._complex,
1022
(<ComplexDoubleElement>right)._complex))
1023
1024
cpdef RingElement _div_(self, RingElement right):
1025
"""
1026
Divide self by right.
1027
1028
EXAMPLES::
1029
1030
sage: CDF(2,-3)._div_(CDF(1,-2))
1031
1.6 + 0.2*I
1032
"""
1033
return self._new_c(gsl_complex_div(self._complex, (<ComplexDoubleElement>right)._complex))
1034
1035
def __invert__(self):
1036
r"""
1037
This function returns the inverse, or reciprocal, of the complex
1038
number `z`,
1039
1040
.. math::
1041
1042
1/z = (x - i y)/(x^2 + y^2).
1043
1044
1045
1046
EXAMPLES::
1047
1048
sage: ~CDF(2,1)
1049
0.4 - 0.2*I
1050
sage: 1/CDF(2,1)
1051
0.4 - 0.2*I
1052
1053
The inverse of 0 is nan (it doesn't raise an exception)::
1054
1055
sage: ~(0*CDF(0,1))
1056
NaN + NaN*I
1057
"""
1058
return self._new_c(gsl_complex_inverse(self._complex))
1059
1060
cpdef ModuleElement _neg_(self):
1061
"""
1062
This function returns the negative of the complex number
1063
`z`,
1064
.. math::
1065
1066
-z = (-x) + i(-y).
1067
1068
1069
EXAMPLES::
1070
1071
sage: -CDF(2,1)
1072
-2.0 - 1.0*I
1073
"""
1074
return self._new_c(gsl_complex_negative(self._complex))
1075
1076
def conjugate(self):
1077
r"""
1078
This function returns the complex conjugate of the complex number
1079
`z`, `\overline{z} = x - i y`.
1080
1081
EXAMPLES::
1082
1083
sage: z = CDF(2,3); z.conjugate()
1084
2.0 - 3.0*I
1085
"""
1086
return self._new_c(gsl_complex_conjugate(self._complex))
1087
1088
def conj(self):
1089
r"""
1090
This function returns the complex conjugate of the complex number
1091
`z`, `\overline{z} = x - i y`.
1092
1093
EXAMPLES::
1094
1095
sage: z = CDF(2,3); z.conj()
1096
2.0 - 3.0*I
1097
"""
1098
return self._new_c(gsl_complex_conjugate(self._complex))
1099
1100
#######################################################################
1101
# Properties of Complex Numbers
1102
#######################################################################
1103
1104
def arg(self):
1105
r"""
1106
This function returns the argument of the complex number
1107
`z`, `\arg(z)`, where
1108
`-\pi < \arg(z) <= \pi`.
1109
1110
EXAMPLES::
1111
1112
sage: CDF(1,0).arg()
1113
0.0
1114
sage: CDF(0,1).arg()
1115
1.57079632679
1116
sage: CDF(0,-1).arg()
1117
-1.57079632679
1118
sage: CDF(-1,0).arg()
1119
3.14159265359
1120
"""
1121
return RealDoubleElement(gsl_complex_arg(self._complex))
1122
1123
def __abs__(self):
1124
"""
1125
This function returns the magnitude of the complex number
1126
`z`, `|z|`.
1127
1128
EXAMPLES::
1129
1130
sage: abs(CDF(1,2))
1131
2.2360679775
1132
sage: abs(CDF(1,0))
1133
1.0
1134
sage: abs(CDF(-2,3)) # slightly random-ish arch dependent output
1135
3.6055512754639891
1136
"""
1137
return RealDoubleElement(gsl_complex_abs(self._complex))
1138
1139
def abs(self):
1140
"""
1141
This function returns the magnitude `|z|` of the complex number
1142
`z`.
1143
1144
.. SEEALSO::
1145
1146
- :meth:`norm`
1147
1148
EXAMPLES::
1149
1150
sage: CDF(2,3).abs() # slightly random-ish arch dependent output
1151
3.6055512754639891
1152
"""
1153
return RealDoubleElement(gsl_complex_abs(self._complex))
1154
1155
def argument(self):
1156
r"""
1157
This function returns the argument of the self, in the interval
1158
`-\pi < arg(self) \le \pi`.
1159
1160
EXAMPLES::
1161
1162
sage: CDF(6).argument()
1163
0.0
1164
sage: CDF(i).argument()
1165
1.57079632679
1166
sage: CDF(-1).argument()
1167
3.14159265359
1168
sage: CDF(-1 - 0.000001*i).argument()
1169
-3.14159165359
1170
"""
1171
return RealDoubleElement(gsl_complex_arg(self._complex))
1172
1173
def abs2(self):
1174
"""
1175
This function returns the squared magnitude `|z|^2` of the complex
1176
number `z`, otherwise known as the complex norm.
1177
1178
.. SEEALSO::
1179
1180
- :meth:`norm`
1181
1182
EXAMPLES::
1183
1184
sage: CDF(2,3).abs2()
1185
13.0
1186
"""
1187
return RealDoubleElement(gsl_complex_abs2(self._complex))
1188
1189
def norm(self):
1190
r"""
1191
This function returns the squared magnitude `|z|^2` of the complex
1192
number `z`, otherwise known as the complex norm. If `c = a + bi`
1193
is a complex number, then the norm of `c` is defined as the product of
1194
`c` and its complex conjugate
1195
1196
.. MATH::
1197
1198
\text{norm}(c)
1199
=
1200
\text{norm}(a + bi)
1201
=
1202
c \cdot \overline{c}
1203
=
1204
a^2 + b^2.
1205
1206
The norm of a complex number is different from its absolute value.
1207
The absolute value of a complex number is defined to be the square
1208
root of its norm. A typical use of the complex norm is in the
1209
integral domain `\ZZ[i]` of Gaussian integers, where the norm of
1210
each Gaussian integer `c = a + bi` is defined as its complex norm.
1211
1212
.. SEEALSO::
1213
1214
- :meth:`abs`
1215
1216
- :meth:`abs2`
1217
1218
- :func:`sage.misc.functional.norm`
1219
1220
- :meth:`sage.rings.complex_number.ComplexNumber.norm`
1221
1222
EXAMPLES::
1223
1224
sage: CDF(2,3).norm()
1225
13.0
1226
"""
1227
return RealDoubleElement(gsl_complex_abs2(self._complex))
1228
1229
def logabs(self):
1230
r"""
1231
This function returns the natural logarithm of the magnitude of the
1232
complex number `z`, `\log|z|`.
1233
1234
This allows for an accurate evaluation of `\log|z|` when
1235
`|z|` is close to `1`. The direct evaluation of
1236
``log(abs(z))`` would lead to a loss of precision in
1237
this case.
1238
1239
EXAMPLES::
1240
1241
sage: CDF(1.1,0.1).logabs()
1242
0.0994254293726
1243
sage: log(abs(CDF(1.1,0.1)))
1244
0.0994254293726
1245
1246
::
1247
1248
sage: log(abs(ComplexField(200)(1.1,0.1)))
1249
0.099425429372582595066319157757531449594489450091985182495705
1250
"""
1251
return RealDoubleElement(gsl_complex_logabs(self._complex))
1252
1253
def real(self):
1254
"""
1255
Return the real part of this complex double.
1256
1257
EXAMPLES::
1258
1259
sage: a = CDF(3,-2)
1260
sage: a.real()
1261
3.0
1262
sage: a.real_part()
1263
3.0
1264
"""
1265
return RealDoubleElement(self._complex.dat[0])
1266
1267
real_part = real
1268
1269
def imag(self):
1270
"""
1271
Return the imaginary part of this complex double.
1272
1273
EXAMPLES::
1274
1275
sage: a = CDF(3,-2)
1276
sage: a.imag()
1277
-2.0
1278
sage: a.imag_part()
1279
-2.0
1280
"""
1281
return RealDoubleElement(self._complex.dat[1])
1282
1283
imag_part = imag
1284
1285
def parent(self):
1286
"""
1287
Return the complex double field, which is the parent of self.
1288
1289
EXAMPLES::
1290
1291
sage: a = CDF(2,3)
1292
sage: a.parent()
1293
Complex Double Field
1294
sage: parent(a)
1295
Complex Double Field
1296
"""
1297
return CDF
1298
1299
1300
#######################################################################
1301
# Elementary Complex Functions
1302
#######################################################################
1303
def sqrt(self, all=False, **kwds):
1304
r"""
1305
The square root function.
1306
1307
INPUT:
1308
1309
1310
- ``all`` - bool (default: False); if True, return a
1311
list of all square roots.
1312
1313
1314
If all is False, the branch cut is the negative real axis. The
1315
result always lies in the right half of the complex plane.
1316
1317
EXAMPLES: We compute several square roots.
1318
1319
::
1320
1321
sage: a = CDF(2,3)
1322
sage: b = a.sqrt(); b
1323
1.67414922804 + 0.89597747613*I
1324
sage: b^2
1325
2.0 + 3.0*I
1326
sage: a^(1/2)
1327
1.67414922804 + 0.89597747613*I
1328
1329
We compute the square root of -1.
1330
1331
::
1332
1333
sage: a = CDF(-1)
1334
sage: a.sqrt()
1335
1.0*I
1336
1337
We compute all square roots::
1338
1339
sage: CDF(-2).sqrt(all=True)
1340
[1.41421356237*I, -1.41421356237*I]
1341
sage: CDF(0).sqrt(all=True)
1342
[0.0]
1343
"""
1344
z = self._new_c(gsl_complex_sqrt(self._complex))
1345
if all:
1346
if z.is_zero():
1347
return [z]
1348
else:
1349
return [z, -z]
1350
return z
1351
1352
def nth_root(self, n, all=False):
1353
"""
1354
The n-th root function.
1355
1356
INPUT:
1357
1358
1359
- ``all`` - bool (default: False); if True, return a
1360
list of all n-th roots.
1361
1362
1363
EXAMPLES::
1364
1365
sage: a = CDF(125)
1366
sage: a.nth_root(3)
1367
5.0
1368
sage: a = CDF(10, 2)
1369
sage: [r^5 for r in a.nth_root(5, all=True)]
1370
[10.0 + 2.0*I, 10.0 + 2.0*I, 10.0 + 2.0*I, 10.0 + 2.0*I, 10.0 + 2.0*I]
1371
sage: abs(sum(a.nth_root(111, all=True))) # random but close to zero
1372
6.00659385991e-14
1373
"""
1374
if not self:
1375
return [self] if all else self
1376
arg = self.argument() / n
1377
abs = self.abs().nth_root(n)
1378
z = ComplexDoubleElement(abs * arg.cos(), abs*arg.sin())
1379
if all:
1380
zeta = self._parent.zeta(n)
1381
return [z * zeta**k for k in range(n)]
1382
else:
1383
return z
1384
1385
1386
def is_square(self):
1387
"""
1388
This function always returns true as `\CC` is algebraically
1389
closed.
1390
1391
EXAMPLES::
1392
1393
sage: CDF(-1).is_square()
1394
True
1395
"""
1396
return True
1397
1398
def _pow_(self, ComplexDoubleElement a):
1399
"""
1400
The function returns the complex number `z` raised to the
1401
complex power `a`, `z^a`.
1402
1403
INPUT:
1404
1405
1406
- ``self, a`` - both of type ComplexDoubleElement
1407
1408
1409
OUTPUT: ComplexDoubleElement
1410
1411
EXAMPLES::
1412
1413
sage: a = CDF(1,1); b = CDF(2,3)
1414
sage: a._pow_(b)
1415
-0.163450932107 + 0.0960049836089*I
1416
"""
1417
return self._new_c(gsl_complex_pow(self._complex, a._complex))
1418
1419
def __pow__(z, a, dummy):
1420
r"""
1421
The function returns the complex number `z` raised to the
1422
complex power `a`, `z^a`.
1423
1424
This is computed as `\exp(\log(z)*a)` using complex
1425
logarithms and complex exponentials.
1426
1427
EXAMPLES::
1428
1429
sage: a = CDF(1,1); b = CDF(2,3)
1430
sage: c = a^b; c
1431
-0.163450932107 + 0.0960049836089*I
1432
sage: c^(1/b)
1433
1.0 + 1.0*I
1434
1435
We compute the cube root of `-1` then cube it and observe a
1436
rounding error::
1437
1438
sage: a = CDF(-1)^(1/3); a
1439
0.5 + 0.866025403784*I
1440
sage: a^3 # slightly random-ish arch dependent output
1441
-1.0 + 1.22460635382e-16*I
1442
1443
We raise to symbolic powers::
1444
1445
sage: x, n = var('x, n')
1446
sage: CDF(1.2)^x
1447
1.2^x
1448
sage: CDF(1.2)^(x^n + n^x)
1449
1.2^(n^x + x^n)
1450
"""
1451
try:
1452
return z._pow_(a)
1453
except AttributeError:
1454
# z is not a complex number
1455
return CDF(z)._pow_(a)
1456
except TypeError:
1457
# a is not a complex number
1458
try:
1459
return z._pow_(CDF(a))
1460
except TypeError:
1461
try:
1462
return a.parent()(z)**a
1463
except AttributeError:
1464
raise TypeError
1465
1466
1467
def exp(self):
1468
r"""
1469
This function returns the complex exponential of the complex number
1470
`z`, `\exp(z)`.
1471
1472
EXAMPLES::
1473
1474
sage: CDF(1,1).exp()
1475
1.46869393992 + 2.28735528718*I
1476
1477
We numerically verify a famous identity to the precision of a
1478
double.
1479
1480
::
1481
1482
sage: z = CDF(0, 2*pi); z
1483
6.28318530718*I
1484
sage: exp(z) # somewhat random-ish output depending on platform
1485
1.0 - 2.44921270764e-16*I
1486
"""
1487
return self._new_c(gsl_complex_exp(self._complex))
1488
1489
def log(self, base=None):
1490
r"""
1491
This function returns the complex natural logarithm to the given
1492
base of the complex number `z`, `\log(z)`. The
1493
branch cut is the negative real axis.
1494
1495
INPUT:
1496
1497
1498
- ``base`` - default: e, the base of the natural
1499
logarithm
1500
1501
1502
EXAMPLES::
1503
1504
sage: CDF(1,1).log()
1505
0.34657359028 + 0.785398163397*I
1506
1507
This is the only example different from the GSL::
1508
1509
sage: CDF(0,0).log()
1510
-infinity
1511
"""
1512
if self == 0:
1513
return RDF(0).log()
1514
if base is None:
1515
return self._new_c(gsl_complex_log(self._complex))
1516
cdef ComplexDoubleElement z
1517
try:
1518
z = base
1519
except TypeError:
1520
z = CDF(base)
1521
return self._new_c(gsl_complex_log_b(self._complex, z._complex))
1522
1523
def log10(self):
1524
r"""
1525
This function returns the complex base-10 logarithm of the complex
1526
number `z`, `\log_{10}(z)`.
1527
1528
The branch cut is the negative real axis.
1529
1530
EXAMPLES::
1531
1532
sage: CDF(1,1).log10()
1533
0.150514997832 + 0.34109408846*I
1534
"""
1535
if self == 0:
1536
return RDF(0).log()
1537
return self._new_c(gsl_complex_log10(self._complex))
1538
1539
def log_b(self, b):
1540
r"""
1541
This function returns the complex base-`b` logarithm of the
1542
complex number `z`, `\log_b(z)`. This quantity is
1543
computed as the ratio `\log(z)/\log(b)`.
1544
1545
The branch cut is the negative real axis.
1546
1547
EXAMPLES::
1548
1549
sage: CDF(1,1).log_b(10)
1550
0.150514997832 + 0.34109408846*I
1551
"""
1552
cdef ComplexDoubleElement _b
1553
if self == 0:
1554
return RDF(0).log()
1555
try:
1556
_b = b
1557
except TypeError:
1558
_b = CDF(b)
1559
return self._new_c(gsl_complex_log_b(self._complex, _b._complex))
1560
1561
#######################################################################
1562
# Complex Trigonometric Functions
1563
#######################################################################
1564
def sin(self):
1565
r"""
1566
This function returns the complex sine of the complex number
1567
`z`, `\sin(z) = (\exp(iz) - \exp(-iz))/(2i)`.
1568
1569
EXAMPLES::
1570
1571
sage: CDF(1,1).sin()
1572
1.29845758142 + 0.634963914785*I
1573
"""
1574
return self._new_c(gsl_complex_sin(self._complex))
1575
1576
def cos(self):
1577
r"""
1578
This function returns the complex cosine of the complex number z,
1579
`\cos(z) = (\exp(iz) + \exp(-iz))/2`.
1580
1581
EXAMPLES::
1582
1583
sage: CDF(1,1).cos()
1584
0.833730025131 - 0.988897705763*I
1585
"""
1586
return self._new_c(gsl_complex_cos(self._complex))
1587
1588
def tan(self):
1589
r"""
1590
This function returns the complex tangent of the complex number z,
1591
`\tan(z) = \sin(z)/\cos(z)`.
1592
1593
EXAMPLES::
1594
1595
sage: CDF(1,1).tan()
1596
0.27175258532 + 1.08392332734*I
1597
"""
1598
return self._new_c(gsl_complex_tan(self._complex))
1599
1600
def sec(self):
1601
r"""
1602
This function returns the complex secant of the complex number
1603
`z`, `{\rm sec}(z) = 1/\cos(z)`.
1604
1605
EXAMPLES::
1606
1607
sage: CDF(1,1).sec()
1608
0.498337030555 + 0.591083841721*I
1609
"""
1610
return self._new_c(gsl_complex_sec(self._complex))
1611
1612
def csc(self):
1613
r"""
1614
This function returns the complex cosecant of the complex number
1615
`z`, `\csc(z) = 1/\sin(z)`.
1616
1617
EXAMPLES::
1618
1619
sage: CDF(1,1).csc()
1620
0.62151801717 - 0.303931001628*I
1621
"""
1622
return self._new_c(gsl_complex_csc(self._complex))
1623
1624
def cot(self):
1625
r"""
1626
This function returns the complex cotangent of the complex number
1627
`z`, `\cot(z) = 1/\tan(z)`.
1628
1629
EXAMPLES::
1630
1631
sage: CDF(1,1).cot()
1632
0.217621561854 - 0.868014142896*I
1633
"""
1634
return self._new_c(gsl_complex_cot(self._complex))
1635
1636
#######################################################################
1637
# Inverse Complex Trigonometric Functions
1638
#######################################################################
1639
def arcsin(self):
1640
r"""
1641
This function returns the complex arcsine of the complex number
1642
`z`, `{\rm arcsin}(z)`. The branch cuts are on the
1643
real axis, less than -1 and greater than 1.
1644
1645
EXAMPLES::
1646
1647
sage: CDF(1,1).arcsin()
1648
0.666239432493 + 1.06127506191*I
1649
"""
1650
return self._new_c(gsl_complex_arcsin(self._complex))
1651
1652
def arccos(self):
1653
r"""
1654
This function returns the complex arccosine of the complex number
1655
`z`, `{\rm arccos}(z)`. The branch cuts are on the
1656
real axis, less than -1 and greater than 1.
1657
1658
EXAMPLES::
1659
1660
sage: CDF(1,1).arccos()
1661
0.904556894302 - 1.06127506191*I
1662
"""
1663
return self._new_c(gsl_complex_arccos(self._complex))
1664
1665
def arctan(self):
1666
r"""
1667
This function returns the complex arctangent of the complex number
1668
`z`, `{\rm arctan}(z)`. The branch cuts are on the
1669
imaginary axis, below `-i` and above `i`.
1670
1671
EXAMPLES::
1672
1673
sage: CDF(1,1).arctan()
1674
1.0172219679 + 0.402359478109*I
1675
"""
1676
return self._new_c(gsl_complex_arctan(self._complex))
1677
1678
def arccsc(self):
1679
r"""
1680
This function returns the complex arccosecant of the complex number
1681
`z`, `{\rm arccsc}(z) = {\rm arcsin}(1/z)`.
1682
1683
EXAMPLES::
1684
1685
sage: CDF(1,1).arccsc()
1686
0.452278447151 - 0.530637530953*I
1687
"""
1688
return self._new_c(gsl_complex_arccsc(self._complex))
1689
1690
def arccot(self):
1691
r"""
1692
This function returns the complex arccotangent of the complex
1693
number `z`, `{\rm arccot}(z) = {\rm arctan}(1/z).`
1694
1695
EXAMPLES::
1696
1697
sage: CDF(1,1).arccot()
1698
0.553574358897 - 0.402359478109*I
1699
"""
1700
return self._new_c(gsl_complex_arccot(self._complex))
1701
1702
1703
#######################################################################
1704
# Complex Hyperbolic Functions
1705
#######################################################################
1706
def sinh(self):
1707
r"""
1708
This function returns the complex hyperbolic sine of the complex
1709
number `z`, `\sinh(z) = (\exp(z) - \exp(-z))/2`.
1710
1711
EXAMPLES::
1712
1713
sage: CDF(1,1).sinh()
1714
0.634963914785 + 1.29845758142*I
1715
"""
1716
return self._new_c(gsl_complex_sinh(self._complex))
1717
1718
def cosh(self):
1719
r"""
1720
This function returns the complex hyperbolic cosine of the complex
1721
number `z`, `\cosh(z) = (\exp(z) + \exp(-z))/2`.
1722
1723
EXAMPLES::
1724
1725
sage: CDF(1,1).cosh()
1726
0.833730025131 + 0.988897705763*I
1727
"""
1728
return self._new_c(gsl_complex_cosh(self._complex))
1729
1730
def tanh(self):
1731
r"""
1732
This function returns the complex hyperbolic tangent of the complex
1733
number `z`, `\tanh(z) = \sinh(z)/\cosh(z)`.
1734
1735
EXAMPLES::
1736
1737
sage: CDF(1,1).tanh()
1738
1.08392332734 + 0.27175258532*I
1739
"""
1740
return self._new_c(gsl_complex_tanh(self._complex))
1741
1742
1743
def sech(self):
1744
r"""
1745
This function returns the complex hyperbolic secant of the complex
1746
number `z`, `{\rm sech}(z) = 1/{\rm cosh}(z)`.
1747
1748
EXAMPLES::
1749
1750
sage: CDF(1,1).sech()
1751
0.498337030555 - 0.591083841721*I
1752
"""
1753
return self._new_c(gsl_complex_sech(self._complex))
1754
1755
def csch(self):
1756
r"""
1757
This function returns the complex hyperbolic cosecant of the
1758
complex number `z`,
1759
`{\rm csch}(z) = 1/{\rm sinh}(z)`.
1760
1761
EXAMPLES::
1762
1763
sage: CDF(1,1).csch()
1764
0.303931001628 - 0.62151801717*I
1765
"""
1766
return self._new_c(gsl_complex_csch(self._complex))
1767
1768
def coth(self):
1769
r"""
1770
This function returns the complex hyperbolic cotangent of the
1771
complex number `z`, `\coth(z) = 1/\tanh(z)`.
1772
1773
EXAMPLES::
1774
1775
sage: CDF(1,1).coth()
1776
0.868014142896 - 0.217621561854*I
1777
"""
1778
return self._new_c(gsl_complex_coth(self._complex))
1779
1780
#######################################################################
1781
# Inverse Complex Hyperbolic Functions
1782
#######################################################################
1783
def arcsinh(self):
1784
r"""
1785
This function returns the complex hyperbolic arcsine of the complex
1786
number `z`, `{\rm arcsinh}(z)`. The branch cuts are
1787
on the imaginary axis, below -i and above i.
1788
1789
EXAMPLES::
1790
1791
sage: CDF(1,1).arcsinh()
1792
1.06127506191 + 0.666239432493*I
1793
"""
1794
return self._new_c(gsl_complex_arcsinh(self._complex))
1795
1796
def arccosh(self):
1797
r"""
1798
This function returns the complex hyperbolic arccosine of the
1799
complex number `z`, `{\rm arccosh}(z)`. The branch
1800
cut is on the real axis, less than 1.
1801
1802
EXAMPLES::
1803
1804
sage: CDF(1,1).arccosh()
1805
1.06127506191 + 0.904556894302*I
1806
"""
1807
return self._new_c(gsl_complex_arccosh(self._complex))
1808
1809
def arctanh(self):
1810
r"""
1811
This function returns the complex hyperbolic arctangent of the
1812
complex number `z`, `{\rm arctanh} (z)`. The branch
1813
cuts are on the real axis, less than -1 and greater than 1.
1814
1815
EXAMPLES::
1816
1817
sage: CDF(1,1).arctanh()
1818
0.402359478109 + 1.0172219679*I
1819
"""
1820
return self._new_c(gsl_complex_arctanh(self._complex))
1821
1822
def arcsech(self):
1823
r"""
1824
This function returns the complex hyperbolic arcsecant of the
1825
complex number `z`,
1826
`{\rm arcsech}(z) = {\rm arccosh}(1/z)`.
1827
1828
EXAMPLES::
1829
1830
sage: CDF(1,1).arcsech()
1831
0.530637530953 - 1.11851787964*I
1832
"""
1833
return self._new_c(gsl_complex_arcsech(self._complex))
1834
1835
def arccsch(self):
1836
r"""
1837
This function returns the complex hyperbolic arccosecant of the
1838
complex number `z`,
1839
`{\rm arccsch}(z) = {\rm arcsin}(1/z)`.
1840
1841
EXAMPLES::
1842
1843
sage: CDF(1,1).arccsch()
1844
0.530637530953 - 0.452278447151*I
1845
"""
1846
return self._new_c(gsl_complex_arccsch(self._complex))
1847
1848
def arccoth(self):
1849
r"""
1850
This function returns the complex hyperbolic arccotangent of the
1851
complex number `z`,
1852
`{\rm arccoth}(z) = {\rm arctanh(1/z)}`.
1853
1854
EXAMPLES::
1855
1856
sage: CDF(1,1).arccoth()
1857
0.402359478109 - 0.553574358897*I
1858
"""
1859
return self._new_c(gsl_complex_arccoth(self._complex))
1860
1861
#######################################################################
1862
# Special Functions (from PARI)
1863
#######################################################################
1864
def eta(self, int omit_frac=0):
1865
r"""
1866
Return the value of the Dedekind `\eta` function on self,
1867
intelligently computed using `\mathbb{SL}(2,\ZZ)`
1868
transformations.
1869
1870
INPUT:
1871
1872
1873
- ``self`` - element of the upper half plane (if not,
1874
raises a ValueError).
1875
1876
- ``omit_frac`` - (bool, default: False), if True,
1877
omit the `e^{\pi i z / 12}` factor.
1878
1879
1880
OUTPUT: a complex double number
1881
1882
ALGORITHM: Uses the PARI C library, but with some modifications so
1883
it always works instead of failing on easy cases involving large
1884
input (like PARI does).
1885
1886
The `\eta` function is
1887
1888
.. math::
1889
1890
\eta(z) = e^{\pi i z / 12} \prod_{n=1}^{\infty} (1 - e^{2\pi inz})
1891
1892
1893
1894
EXAMPLES: We compute a few values of eta::
1895
1896
sage: CDF(0,1).eta()
1897
0.768225422326
1898
sage: CDF(1,1).eta()
1899
0.742048775837 + 0.19883137023*I
1900
sage: CDF(25,1).eta()
1901
0.742048775837 + 0.19883137023*I
1902
1903
Eta works even if the inputs are large.
1904
1905
::
1906
1907
sage: CDF(0,10^15).eta()
1908
0.0
1909
sage: CDF(10^15,0.1).eta() # slightly random-ish arch dependent output
1910
-0.121339721991 - 0.19619461894*I
1911
1912
We compute a few values of eta, but with the fractional power of e
1913
omitted.
1914
1915
::
1916
1917
sage: CDF(0,1).eta(True)
1918
0.998129069926
1919
1920
We compute eta to low precision directly from the definition.
1921
1922
::
1923
1924
sage: z = CDF(1,1); z.eta()
1925
0.742048775837 + 0.19883137023*I
1926
sage: i = CDF(0,1); pi = CDF(pi)
1927
sage: exp(pi * i * z / 12) * prod([1-exp(2*pi*i*n*z) for n in range(1,10)])
1928
0.742048775837 + 0.19883137023*I
1929
1930
The optional argument allows us to omit the fractional part::
1931
1932
sage: z = CDF(1,1)
1933
sage: z.eta(omit_frac=True)
1934
0.998129069926
1935
sage: pi = CDF(pi)
1936
sage: prod([1-exp(2*pi*i*n*z) for n in range(1,10)]) # slightly random-ish arch dependent output
1937
0.998129069926 + 4.5908467128e-19*I
1938
1939
We illustrate what happens when `z` is not in the upper
1940
half plane.
1941
1942
::
1943
1944
sage: z = CDF(1)
1945
sage: z.eta()
1946
Traceback (most recent call last):
1947
...
1948
ValueError: value must be in the upper half plane
1949
1950
You can also use functional notation.
1951
1952
::
1953
1954
sage: z = CDF(1,1) ; eta(z)
1955
0.742048775837 + 0.19883137023*I
1956
"""
1957
cdef GEN a, b, c, y, t
1958
1959
# Turn on Sage C interrupt handling. There must
1960
# be no Python code between here and sig_off().
1961
#sig_on() # we're not using this since it would dominate the runtime
1962
1963
if self._complex.dat[1] <= 0:
1964
raise ValueError, "value must be in the upper half plane"
1965
1966
if self._complex.dat[1] > 100000:
1967
# To the precision of doubles for such large imaginary
1968
# part the answer is automatically 0. If we don't do
1969
# this PARI can easily die, which will cause this function
1970
# to bomb unless we use sig_on() and sig_off(). But
1971
# I don't want to use those, since they take more time
1972
# than this entire function! Moreover, I don't want Sage's
1973
# eta to every bomb -- this function should work on all input; there's
1974
# no excuse for having it fail on easy edge cases (like PARI does).
1975
return ComplexDoubleElement(0,0)
1976
1977
# save position on PARI stack
1978
cdef pari_sp sp
1979
global avma
1980
sp = avma
1981
1982
# If omit_frac is True, then eta(z) = eta(z+24*n) for any integer n,
1983
# so we can replace the real part of self by its fractional part. We
1984
# do this for two reasons:
1985
# (1) Because when the real part is sufficiently large, PARI overflows
1986
# and crashes, and I don't want to use sig_on()/sig_off() to catch this.
1987
# (2) Because this is easy and it makes it so our eta always works,
1988
# unlike PARI's.
1989
# convert our complex number to a PARI number
1990
# If omit_frac is False, then eta(z) = eta(z+24*n) for any integer n,
1991
# and similar remarks apply.
1992
cdef double dummy
1993
a = dbltor(modf(self._complex.dat[0], &dummy)) # see big comment above
1994
b = dbltor(self._complex.dat[1])
1995
1996
y = cgetg(3, t_COMPLEX) # allocate space for a complex number
1997
set_gel(y,1,a); set_gel(y,2,b)
1998
1999
c = eta(y, PREC)
2000
2001
# Convert the PARI complex number c back to a GSL complex number
2002
cdef gsl_complex w
2003
w = gsl_complex_rect(rtodbl(greal(c)), rtodbl(gimag(c)))
2004
2005
# put the pari stack back; this frees all memory used
2006
# by PARI above.
2007
avma = sp
2008
2009
if not omit_frac:
2010
# multiply z by e^{\pi i z / 12} = exp(pi * i * z / 12), where z = self.
2011
w = gsl_complex_mul(w, gsl_complex_exp(gsl_complex_mul(\
2012
gsl_complex_rect(0,M_PI_4/(<double>3)), self._complex)))
2013
2014
return self._new_c(w)
2015
2016
def agm(self, right, algorithm="optimal"):
2017
"""
2018
Return the Arithmetic-Geometric Mean (AGM) of self and right.
2019
2020
INPUT:
2021
2022
- right (complex) -- another complex number
2023
2024
- algorithm (string, default "optimal") -- the algorithm to use
2025
(see below).
2026
2027
OUTPUT:
2028
2029
(complex) A value of the AGM of self and right. Note that
2030
this is a multi-valued function, and the algorithm used
2031
affects the value returned, as follows:
2032
2033
- "pari": Call the agm function from the pari library.
2034
2035
- "optimal": Use the AGM sequence such that at each stage
2036
`(a,b)` is replaced by `(a_1,b_1)=((a+b)/2,\pm\sqrt{ab})`
2037
where the sign is chosen so that `|a_1-b_1|\le|a_1+b_1|`, or
2038
equivalently `\Re(b_1/a_1)\ge0`. The resulting limit is
2039
maximal among all possible values.
2040
2041
- "principal": Use the AGM sequence such that at each stage
2042
`(a,b)` is replaced by `(a_1,b_1)=((a+b)/2,\pm\sqrt{ab})`
2043
where the sign is chosen so that `\Re(b_1/a_1)\ge0` (the
2044
so-called principal branch of the square root).
2045
2046
EXAMPLES::
2047
2048
sage: i = CDF(I)
2049
sage: (1+i).agm(2-i)
2050
1.62780548487 + 0.136827548397*I
2051
2052
An example to show that the returned value depends on the algorithm parameter::
2053
2054
sage: a = CDF(-0.95,-0.65)
2055
sage: b = CDF(0.683,0.747)
2056
sage: a.agm(b, algorithm='optimal')
2057
-0.371591652352 + 0.319894660207*I
2058
sage: a.agm(b, algorithm='principal')
2059
0.338175462986 - 0.0135326969565*I
2060
sage: a.agm(b, algorithm='pari')
2061
0.080689185076 + 0.239036532686*I
2062
2063
Some degenerate cases::
2064
2065
sage: CDF(0).agm(a)
2066
0.0
2067
sage: a.agm(0)
2068
0.0
2069
sage: a.agm(-a)
2070
0.0
2071
"""
2072
cdef double complex a, b, a1, b1, r
2073
cdef double d, e, eps = 2.0**-51
2074
2075
cdef pari_sp sp
2076
2077
if algorithm=="pari":
2078
sp = avma
2079
return self._new_from_gen_c( agm(self._gen(), complex_gen(right), PREC), sp)
2080
2081
if not isinstance(right, ComplexDoubleElement):
2082
right = CDF(right)
2083
2084
a = extract_double_complex(self)
2085
b = extract_double_complex(<ComplexDoubleElement>right)
2086
2087
if a == 0 or b == 0 or a == -b:
2088
return ComplexDoubleElement(0, 0)
2089
2090
if algorithm=="optimal":
2091
while True:
2092
a1 = (a+b)/2
2093
b1 = csqrt(a*b)
2094
r = b1/a1
2095
d = cabs(r-1)
2096
e = cabs(r+1)
2097
if e < d:
2098
b1=-b1
2099
d = e
2100
if d < eps: return ComplexDoubleElement_from_doubles(a1.real, a1.imag)
2101
a, b = a1, b1
2102
2103
elif algorithm=="principal":
2104
while True:
2105
a1 = (a+b)/2
2106
b1 = csqrt(a*b)
2107
if cabs((b1/a1)-1) < eps: return ComplexDoubleElement_from_doubles(a1.real, a1.imag)
2108
a, b = a1, b1
2109
2110
else:
2111
raise ValueError, "agm algorithm must be one of 'pari', 'optimal', 'principal'"
2112
2113
def dilog(self):
2114
r"""
2115
Returns the principal branch of the dilogarithm of `x`,
2116
i.e., analytic continuation of the power series
2117
2118
.. math::
2119
2120
\log_2(x) = \sum_{n \ge 1} x^n / n^2.
2121
2122
2123
2124
EXAMPLES::
2125
2126
sage: CDF(1,2).dilog()
2127
-0.0594747986738 + 2.07264797177*I
2128
sage: CDF(10000000,10000000).dilog()
2129
-134.411774491 + 38.793962999*I
2130
"""
2131
cdef pari_sp sp
2132
sp = avma
2133
return self._new_from_gen_c( dilog(self._gen(), PREC), sp)
2134
2135
def gamma(self):
2136
"""
2137
Return the Gamma function evaluated at this complex number.
2138
2139
EXAMPLES::
2140
2141
sage: CDF(5,0).gamma()
2142
24.0
2143
sage: CDF(1,1).gamma()
2144
0.498015668118 - 0.154949828302*I
2145
sage: CDF(0).gamma()
2146
Infinity
2147
sage: CDF(-1,0).gamma()
2148
Infinity
2149
"""
2150
if self._complex.dat[1] == 0:
2151
if self._complex.dat[0] == 0:
2152
import infinity
2153
return infinity.unsigned_infinity
2154
try:
2155
from sage.rings.all import Integer, CC
2156
if Integer(self._complex.dat[0]) < 0:
2157
return CC(self).gamma()
2158
except TypeError:
2159
pass
2160
cdef pari_sp sp
2161
sp = avma
2162
return self._new_from_gen_c( ggamma(self._gen(), PREC), sp)
2163
2164
def gamma_inc(self, t):
2165
r"""
2166
Return the incomplete Gamma function evaluated at this complex
2167
number.
2168
2169
EXAMPLES::
2170
2171
sage: CDF(1,1).gamma_inc(CDF(2,3))
2172
0.00209691486365 - 0.0599819136554*I
2173
sage: CDF(1,1).gamma_inc(5)
2174
-0.00137813093622 + 0.00651982002312*I
2175
sage: CDF(2,0).gamma_inc(CDF(1,1))
2176
0.707092096346 - 0.42035364096*I
2177
"""
2178
cdef pari_sp sp
2179
sp = avma
2180
sig_on() # because it is somewhat slow and/or unreliable in corner cases.
2181
x = self._new_from_gen_c( incgam(self._gen(), complex_gen(t), PREC), sp )
2182
sig_off()
2183
return x
2184
2185
def zeta(self):
2186
"""
2187
Return the Riemann zeta function evaluated at this complex number.
2188
2189
EXAMPLES::
2190
2191
sage: z = CDF(1, 1)
2192
sage: z.zeta()
2193
0.582158059752 - 0.926848564331*I
2194
sage: zeta(z)
2195
0.582158059752 - 0.926848564331*I
2196
sage: zeta(CDF(1))
2197
Infinity
2198
"""
2199
if self._complex.dat[0] == 1 and self._complex.dat[1] == 0:
2200
import infinity
2201
return infinity.unsigned_infinity
2202
cdef pari_sp sp
2203
sp = avma
2204
return self._new_from_gen_c( gzeta(self._gen(), PREC), sp)
2205
2206
def algdep(self, long n):
2207
"""
2208
Returns a polynomial of degree at most `n` which is
2209
approximately satisfied by this complex number. Note that the
2210
returned polynomial need not be irreducible, and indeed usually
2211
won't be if `z` is a good approximation to an algebraic
2212
number of degree less than `n`.
2213
2214
ALGORITHM: Uses the PARI C-library algdep command.
2215
2216
EXAMPLE::
2217
2218
sage: z = (1/2)*(1 + RDF(sqrt(3)) *CDF.0); z
2219
0.5 + 0.866025403784*I
2220
sage: p = z.algdep(5); p
2221
x^3 + 1
2222
sage: p.factor()
2223
(x + 1) * (x^2 - x + 1)
2224
sage: abs(z^2 - z + 1) < 1e-14
2225
True
2226
2227
::
2228
2229
sage: CDF(0,2).algdep(10)
2230
x^2 + 4
2231
sage: CDF(1,5).algdep(2)
2232
x^2 - 2*x + 26
2233
"""
2234
cdef sage.libs.pari.gen.PariInstance P
2235
P = sage.libs.pari.gen.pari
2236
sig_on()
2237
f = P.new_gen(algdep0(self._gen(), n, 0))
2238
from polynomial.polynomial_ring_constructor import PolynomialRing
2239
from integer_ring import ZZ
2240
R = PolynomialRing(ZZ ,'x')
2241
return R(list(reversed(eval(str(f.Vec())))))
2242
2243
2244
cdef class FloatToCDF(Morphism):
2245
"""
2246
Fast morphism from anything with a __float__ method to an RDF
2247
element.
2248
2249
EXAMPLES::
2250
2251
sage: f = CDF.coerce_map_from(ZZ); f
2252
Native morphism:
2253
From: Integer Ring
2254
To: Complex Double Field
2255
sage: f(4)
2256
4.0
2257
sage: f = CDF.coerce_map_from(QQ); f
2258
Native morphism:
2259
From: Rational Field
2260
To: Complex Double Field
2261
sage: f(1/2)
2262
0.5
2263
sage: f = CDF.coerce_map_from(int); f
2264
Native morphism:
2265
From: Set of Python objects of type 'int'
2266
To: Complex Double Field
2267
sage: f(3r)
2268
3.0
2269
sage: f = CDF.coerce_map_from(float); f
2270
Native morphism:
2271
From: Set of Python objects of type 'float'
2272
To: Complex Double Field
2273
sage: f(3.5)
2274
3.5
2275
"""
2276
def __init__(self, R):
2277
from sage.categories.homset import Hom
2278
if isinstance(R, type):
2279
from sage.structure.parent import Set_PythonType
2280
R = Set_PythonType(R)
2281
Morphism.__init__(self, Hom(R, CDF))
2282
cpdef Element _call_(self, x):
2283
cdef ComplexDoubleElement z = <ComplexDoubleElement>PY_NEW(ComplexDoubleElement)
2284
z._complex = gsl_complex_rect(x, 0)
2285
return z
2286
def _repr_type(self):
2287
return "Native"
2288
2289
#####################################################
2290
# Create new ComplexDoubleElement from a
2291
# gsl_complex C struct.
2292
#####################################################
2293
2294
cdef GEN complex_gen(x):
2295
"""
2296
INPUT:
2297
2298
- A Python object x
2299
2300
OUTPUT:
2301
2302
- A GEN of type t_COMPLEX, or raise a
2303
TypeError.
2304
"""
2305
cdef ComplexDoubleElement z
2306
global _CDF
2307
try:
2308
z = x
2309
except TypeError:
2310
z = _CDF(x)
2311
return z._gen()
2312
2313
2314
2315
2316
2317
#####################################################
2318
# unique objects
2319
#####################################################
2320
cdef ComplexDoubleField_class _CDF
2321
_CDF = ComplexDoubleField_class()
2322
CDF = _CDF # external interface
2323
cdef ComplexDoubleElement I = ComplexDoubleElement(0,1)
2324
2325
def ComplexDoubleField():
2326
"""
2327
Returns the field of double precision complex numbers.
2328
2329
EXAMPLE::
2330
2331
sage: ComplexDoubleField()
2332
Complex Double Field
2333
sage: ComplexDoubleField() is CDF
2334
True
2335
"""
2336
return _CDF
2337
2338
from sage.misc.parser import Parser
2339
cdef cdf_parser = Parser(float, float, {"I" : _CDF.gen(), "i" : _CDF.gen()})
2340
2341
cdef extern from "math.h":
2342
int isfinite(double x)
2343
int isnan(double x)
2344
int isinf(double x)
2345
2346
cdef double_to_str(double x):
2347
if isfinite(x):
2348
return str(x)
2349
if isnan(x):
2350
return "NaN"
2351
# C99 only guarantees that isinf() returns a nonzero value (actually: 1) if x is an
2352
# infinity (positive or negative). Modern Linux distros return -1 or +1 depending
2353
# on the sign of infinity, but that is not the case on OS X or Solaris
2354
if isinf(x) != 0 and x < 0:
2355
return '-infinity'
2356
elif isinf(x) != 0 and x > 0:
2357
return '+infinity'
2358
2359
cdef inline double complex extract_double_complex(ComplexDoubleElement x):
2360
"""
2361
Return the value of x as a c99 complex double.
2362
"""
2363
cdef double complex z
2364
z.real = x._complex.dat[0]
2365
z.imag = x._complex.dat[1]
2366
return z
2367
2368
cdef ComplexDoubleElement ComplexDoubleElement_from_doubles(double re, double im):
2369
"""
2370
Create a new ComplexDoubleElement with the specified real and imaginary parts.
2371
"""
2372
cdef ComplexDoubleElement z = <ComplexDoubleElement>PY_NEW(ComplexDoubleElement)
2373
z._complex.dat[0] = re
2374
z._complex.dat[1] = im
2375
return z
2376
2377
#####
2378
2379