This repository has been archived by the owner on Jan 30, 2023. It is now read-only.
/
complex_double.pyx
2594 lines (2022 loc) · 74.4 KB
/
complex_double.pyx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
r"""
Double Precision Complex Numbers
Sage supports arithmetic using double-precision complex numbers. A
double-precision complex number is a complex number ``x + I*y`` with
`x`, `y` 64-bit (8 byte) floating point numbers (double precision).
The field :class:`ComplexDoubleField` implements the field
of all double-precision complex numbers. You can refer to this
field by the shorthand CDF. Elements of this field are of type
:class:`ComplexDoubleElement`. If `x` and `y` are coercible to
doubles, you can create a complex double element using
``ComplexDoubleElement(x,y)``. You can coerce more
general objects `z` to complex doubles by typing either
``ComplexDoubleField(x)`` or ``CDF(x)``.
EXAMPLES::
sage: ComplexDoubleField()
Complex Double Field
sage: CDF
Complex Double Field
sage: type(CDF.0)
<type 'sage.rings.complex_double.ComplexDoubleElement'>
sage: ComplexDoubleElement(sqrt(2),3)
1.4142135623730951 + 3.0*I
sage: parent(CDF(-2))
Complex Double Field
::
sage: CC == CDF
False
sage: CDF is ComplexDoubleField() # CDF is the shorthand
True
sage: CDF == ComplexDoubleField()
True
The underlying arithmetic of complex numbers is implemented using
functions and macros in GSL (the GNU Scientific Library), and
should be very fast. Also, all standard complex trig functions,
log, exponents, etc., are implemented using GSL, and are also
robust and fast. Several other special functions, e.g. eta, gamma,
incomplete gamma, etc., are implemented using the PARI C library.
AUTHORS:
- William Stein (2006-09): first version
- Travis Scrimshaw (2012-10-18): Added doctests to get full coverage
- Jeroen Demeyer (2013-02-27): fixed all PARI calls (:trac:`14082`)
- Vincent Klein (2017-11-15) : add __mpc__() to class ComplexDoubleElement.
ComplexDoubleElement constructor support and gmpy2.mpc parameter.
"""
# ****************************************************************************
# Copyright (C) 2006 William Stein <wstein@gmail.com>
# Copyright (C) 2013 Jeroen Demeyer <jdemeyer@cage.ugent.be>
#
# Distributed under the terms of the GNU General Public License (GPL)
# as published by the Free Software Foundation; either version 2 of
# the License, or (at your option) any later version.
# https://www.gnu.org/licenses/
# ****************************************************************************
from __future__ import absolute_import, print_function
import operator
from cpython.object cimport Py_NE
from cysignals.signals cimport sig_on, sig_off
from sage.misc.randstate cimport randstate, current_randstate
from cypari2.paridecl cimport *
from sage.libs.gsl.complex cimport *
cdef extern from "<complex.h>":
double complex csqrt(double complex)
double cabs(double complex)
cimport sage.rings.ring
cimport sage.rings.integer
from sage.structure.element cimport RingElement, Element, ModuleElement, FieldElement
from sage.structure.parent cimport Parent
from sage.structure.parent_gens import ParentWithGens
from sage.structure.richcmp cimport rich_to_bool
from sage.categories.morphism cimport Morphism
from sage.structure.coerce cimport is_numpy_type
from cypari2.gen cimport Gen as pari_gen
from cypari2.convert cimport new_gen_from_double, new_t_COMPLEX_from_double
from . import complex_number
from .complex_field import ComplexField
cdef CC = ComplexField()
from .real_mpfr import RealField
cdef RR = RealField()
from .real_double cimport RealDoubleElement, double_repr
from .real_double import RDF
from sage.rings.integer_ring import ZZ
IF HAVE_GMPY2:
cimport gmpy2
gmpy2.import_gmpy2()
def is_ComplexDoubleField(x):
"""
Return ``True`` if ``x`` is the complex double field.
EXAMPLES::
sage: from sage.rings.complex_double import is_ComplexDoubleField
sage: is_ComplexDoubleField(CDF)
True
sage: is_ComplexDoubleField(ComplexField(53))
False
"""
return isinstance(x, ComplexDoubleField_class)
cdef class ComplexDoubleField_class(sage.rings.ring.Field):
"""
An approximation to the field of complex numbers using double
precision floating point numbers. Answers derived from calculations
in this approximation may differ from what they would be if those
calculations were performed in the true field of complex numbers.
This is due to the rounding errors inherent to finite precision
calculations.
ALGORITHM:
Arithmetic is done using GSL (the GNU Scientific Library).
"""
def __init__(self):
r"""
Construct field of complex double precision numbers.
EXAMPLES::
sage: from sage.rings.complex_double import ComplexDoubleField_class
sage: CDF == ComplexDoubleField_class()
True
sage: TestSuite(CDF).run(skip = ["_test_prod"])
.. WARNING:: due to rounding errors, one can have `x^2 != x*x`::
sage: x = CDF.an_element()
sage: x
1.0*I
sage: x*x, x**2, x*x == x**2
(-1.0, -1.0 + 1.2246...e-16*I, False)
"""
from sage.categories.fields import Fields
ParentWithGens.__init__(self, self, ('I',), normalize=False, category=Fields().Metric().Complete())
self._populate_coercion_lists_()
def __reduce__(self):
"""
For pickling.
EXAMPLES::
sage: loads(dumps(CDF)) is CDF
True
"""
return ComplexDoubleField, ()
cpdef bint is_exact(self) except -2:
"""
Returns whether or not this field is exact, which is always ``False``.
EXAMPLES::
sage: CDF.is_exact()
False
"""
return False
def __richcmp__(left, right, int op):
"""
Rich comparison of ``left`` against ``right``.
EXAMPLES::
sage: CDF == CDF
True
"""
if left is right:
return rich_to_bool(op, 0)
if isinstance(right, ComplexDoubleField_class):
return rich_to_bool(op, 0)
return op == Py_NE
def __hash__(self):
"""
Return the hash for ``self``.
This class is intended for use as a singleton so any instance
of it should be equivalent from a hashing perspective.
TESTS::
sage: from sage.rings.complex_double import ComplexDoubleField_class
sage: hash(CDF) == hash(ComplexDoubleField_class())
True
"""
return 561162115
def characteristic(self):
"""
Return the characteristic of the complex double field, which is 0.
EXAMPLES::
sage: CDF.characteristic()
0
"""
from .integer import Integer
return Integer(0)
def random_element(self, double xmin=-1, double xmax=1, double ymin=-1, double ymax=1):
"""
Return a random element of this complex double field with real and
imaginary part bounded by ``xmin``, ``xmax``, ``ymin``, ``ymax``.
EXAMPLES::
sage: CDF.random_element()
-0.43681052967509904 + 0.7369454235661859*I
sage: CDF.random_element(-10,10,-10,10)
-7.088740263015161 - 9.54135400334003*I
sage: CDF.random_element(-10^20,10^20,-2,2)
-7.587654737635711e+19 + 0.925549022838656*I
"""
cdef randstate rstate = current_randstate()
global _CDF
cdef ComplexDoubleElement z
cdef double imag = (ymax-ymin)*rstate.c_rand_double() + ymin
cdef double real = (xmax-xmin)*rstate.c_rand_double() + xmin
z = ComplexDoubleElement.__new__(ComplexDoubleElement)
z._complex = gsl_complex_rect(real, imag)
return z
def _repr_(self):
"""
Print out this complex double field.
EXAMPLES::
sage: ComplexDoubleField() # indirect doctest
Complex Double Field
sage: CDF # indirect doctest
Complex Double Field
"""
return "Complex Double Field"
def _latex_(self):
r"""
Return a LaTeX representation of ``self``.
OUTPUT:
- a string.
TESTS::
sage: print(CDF._latex_())
\Bold{C}
"""
return r"\Bold{C}"
def __call__(self, x, im=None):
"""
Create a complex double using ``x`` and optionally an imaginary part
``im``.
EXAMPLES::
sage: CDF(0,1) # indirect doctest
1.0*I
sage: CDF(2/3) # indirect doctest
0.6666666666666666
sage: CDF(5) # indirect doctest
5.0
sage: CDF('i') # indirect doctest
1.0*I
sage: CDF(complex(2,-3)) # indirect doctest
2.0 - 3.0*I
sage: CDF(4.5) # indirect doctest
4.5
sage: CDF(1+I) # indirect doctest
1.0 + 1.0*I
sage: CDF(pari(1))
1.0
sage: CDF(pari("I"))
1.0*I
sage: CDF(pari("x^2 + x + 1").polroots()[0])
-0.5 - 0.8660254037844386*I
sage: from gmpy2 import mpc # optional - gmpy2
sage: CDF(mpc('2.0+1.0j')) # optional - gmpy2
2.0 + 1.0*I
A ``TypeError`` is raised if the coercion doesn't make sense::
sage: CDF(QQ['x'].0)
Traceback (most recent call last):
...
TypeError: cannot coerce nonconstant polynomial to float
One can convert back and forth between double precision complex
numbers and higher-precision ones, though of course there may be
loss of precision::
sage: a = ComplexField(200)(-2).sqrt(); a
1.4142135623730950488016887242096980785696718753769480731767*I
sage: b = CDF(a); b
1.4142135623730951*I
sage: a.parent()(b)
1.4142135623730951454746218587388284504413604736328125000000*I
sage: a.parent()(b) == b
True
sage: b == CC(a)
True
"""
# We implement __call__ to gracefully accept the second argument.
if im is not None:
x = x, im
return Parent.__call__(self, x)
def _element_constructor_(self, x):
"""
See ``__call__()``.
EXAMPLES::
sage: CDF((1,2)) # indirect doctest
1.0 + 2.0*I
"""
if isinstance(x, ComplexDoubleElement):
return x
elif isinstance(x, tuple):
return ComplexDoubleElement(x[0], x[1])
elif isinstance(x, (float, int, long)):
return ComplexDoubleElement(x, 0)
elif isinstance(x, complex):
return ComplexDoubleElement(x.real, x.imag)
elif isinstance(x, complex_number.ComplexNumber):
return ComplexDoubleElement(x.real(), x.imag())
elif isinstance(x, pari_gen):
return pari_to_cdf(x)
elif HAVE_GMPY2 and type(x) is gmpy2.mpc:
return ComplexDoubleElement((<gmpy2.mpc>x).real, (<gmpy2.mpc>x).imag)
elif isinstance(x, str):
t = cdf_parser.parse_expression(x)
if isinstance(t, float):
return ComplexDoubleElement(t, 0)
else:
return t
elif hasattr(x, '_complex_double_'):
return x._complex_double_(self)
else:
return ComplexDoubleElement(x, 0)
cpdef _coerce_map_from_(self, S):
"""
Return the canonical coerce of `x` into the complex double field, if
it is defined, otherwise raise a ``TypeError``.
The rings that canonically coerce to the complex double field are:
- the complex double field itself
- anything that canonically coerces to real double field.
- mathematical constants
- the 53-bit mpfr complex field
EXAMPLES::
sage: CDF._coerce_(5) # indirect doctest
5.0
sage: CDF._coerce_(RDF(3.4))
3.4
Thus the sum of a CDF and a symbolic object is symbolic::
sage: a = pi + CDF.0; a
pi + 1.0*I
sage: parent(a)
Symbolic Ring
TESTS::
sage: CDF(1) + RR(1)
2.0
sage: CDF.0 - CC(1) - long(1) - RR(1) - QQbar(1)
-4.0 + 1.0*I
sage: CDF.has_coerce_map_from(ComplexField(20))
False
sage: CDF.has_coerce_map_from(complex)
True
"""
if S is int or S is float:
return FloatToCDF(S)
from .rational_field import QQ
from .real_lazy import RLF
from .real_mpfr import RR, RealField_class
from .complex_field import ComplexField_class
if S is ZZ or S is QQ or S is RDF or S is RLF:
return FloatToCDF(S)
if isinstance(S, RealField_class):
if S.prec() >= 53:
return FloatToCDF(S)
else:
return None
elif is_numpy_type(S):
import numpy
if issubclass(S, numpy.integer) or issubclass(S, numpy.floating):
return FloatToCDF(S)
elif issubclass(S, numpy.complexfloating):
return ComplexToCDF(S)
else:
return None
elif RR.has_coerce_map_from(S):
return FloatToCDF(RR) * RR._internal_coerce_map_from(S)
elif isinstance(S, ComplexField_class) and S.prec() >= 53:
return complex_number.CCtoCDF(S, self)
elif CC.has_coerce_map_from(S):
return complex_number.CCtoCDF(CC, self) * CC._internal_coerce_map_from(S)
def _magma_init_(self, magma):
r"""
Return a string representation of ``self`` in the Magma language.
EXAMPLES::
sage: CDF._magma_init_(magma) # optional - magma
'ComplexField(53 : Bits := true)'
sage: magma(CDF) # optional - magma
Complex field of precision 15
sage: floor(RR(log(2**53, 10)))
15
sage: magma(CDF).sage() # optional - magma
Complex Field with 53 bits of precision
"""
return "ComplexField(%s : Bits := true)" % self.prec()
def _fricas_init_(self):
r"""
Return a string representation of ``self`` in the FriCAS language.
EXAMPLES::
sage: fricas(CDF) # indirect doctest, optional - fricas
Complex(DoubleFloat)
"""
return "Complex DoubleFloat"
def prec(self):
"""
Return the precision of this complex double field (to be more
similar to :class:`ComplexField`). Always returns 53.
EXAMPLES::
sage: CDF.prec()
53
"""
return 53
precision=prec
def to_prec(self, prec):
"""
Returns the complex field to the specified precision. As doubles
have fixed precision, this will only return a complex double field
if prec is exactly 53.
EXAMPLES::
sage: CDF.to_prec(53)
Complex Double Field
sage: CDF.to_prec(250)
Complex Field with 250 bits of precision
"""
if prec == 53:
return self
else:
return ComplexField(prec)
def gen(self, n=0):
"""
Return the generator of the complex double field.
EXAMPLES::
sage: CDF.0
1.0*I
sage: CDF.gen(0)
1.0*I
"""
if n != 0:
raise ValueError("only 1 generator")
return I
def ngens(self):
r"""
The number of generators of this complex field as an `\RR`-algebra.
There is one generator, namely ``sqrt(-1)``.
EXAMPLES::
sage: CDF.ngens()
1
"""
return 1
def algebraic_closure(self):
r"""
Returns the algebraic closure of ``self``, i.e., the complex double
field.
EXAMPLES::
sage: CDF.algebraic_closure()
Complex Double Field
"""
return self
def real_double_field(self):
"""
The real double field, which you may view as a subfield of this
complex double field.
EXAMPLES::
sage: CDF.real_double_field()
Real Double Field
"""
return RDF
def pi(self):
r"""
Returns `\pi` as a double precision complex number.
EXAMPLES::
sage: CDF.pi()
3.141592653589793
"""
return self(3.1415926535897932384626433832)
def construction(self):
"""
Returns the functorial construction of ``self``, namely, algebraic
closure of the real double field.
EXAMPLES::
sage: c, S = CDF.construction(); S
Real Double Field
sage: CDF == c(S)
True
"""
from sage.categories.pushout import AlgebraicClosureFunctor
return (AlgebraicClosureFunctor(), self.real_double_field())
def zeta(self, n=2):
r"""
Return a primitive `n`-th root of unity in this CDF, for
`n \geq 1`.
INPUT:
- ``n`` -- a positive integer (default: 2)
OUTPUT: a complex `n`-th root of unity.
EXAMPLES::
sage: CDF.zeta(7) # rel tol 1e-15
0.6234898018587336 + 0.7818314824680298*I
sage: CDF.zeta(1)
1.0
sage: CDF.zeta()
-1.0
sage: CDF.zeta() == CDF.zeta(2)
True
::
sage: CDF.zeta(0.5)
Traceback (most recent call last):
...
ValueError: n must be a positive integer
sage: CDF.zeta(0)
Traceback (most recent call last):
...
ValueError: n must be a positive integer
sage: CDF.zeta(-1)
Traceback (most recent call last):
...
ValueError: n must be a positive integer
"""
from .integer import Integer
try:
n = Integer(n)
except TypeError:
raise ValueError("n must be a positive integer")
if n<1:
raise ValueError("n must be a positive integer")
if n == 1:
x = self(1)
elif n == 2:
x = self(-1)
elif n >= 3:
# Use De Moivre
# e^(2*pi*i/n) = cos(2pi/n) + i *sin(2pi/n)
pi = RDF.pi()
z = 2*pi/n
x = CDF(z.cos(), z.sin())
# x._set_multiplicative_order( n ) # not implemented for CDF
return x
def _factor_univariate_polynomial(self, f):
"""
Factor the univariate polynomial ``f``.
INPUT:
- ``f`` -- a univariate polynomial defined over the double precision
complex numbers
OUTPUT:
- A factorization of ``f`` over the double precision complex numbers
into a unit and monic irreducible factors
.. NOTE::
This is a helper method for
:meth:`sage.rings.polynomial.polynomial_element.Polynomial.factor`.
TESTS::
sage: R.<x> = CDF[]
sage: CDF._factor_univariate_polynomial(x)
x
sage: CDF._factor_univariate_polynomial(2*x)
(2.0) * x
sage: CDF._factor_univariate_polynomial(x^2)
x^2
sage: f = x^2 + 1
sage: F = CDF._factor_univariate_polynomial(f)
sage: [f(t[0][0]).abs() for t in F] # abs tol 1e-9
[5.55111512313e-17, 6.66133814775e-16]
sage: f = (x^2 + 2*R(I))^3
sage: F = f.factor()
sage: [f(t[0][0]).abs() for t in F] # abs tol 1e-9
[1.979365054e-14, 1.97936298566e-14, 1.97936990747e-14, 3.6812407475e-14, 3.65211563729e-14, 3.65220890052e-14]
"""
unit = f.leading_coefficient()
f *= ~unit
roots = f.roots()
from sage.misc.flatten import flatten
roots = flatten([[r]*m for r, m in roots])
from sage.structure.factorization import Factorization
x = f.parent().gen()
return Factorization([(x - a, 1) for a in roots], unit)
cdef ComplexDoubleElement new_ComplexDoubleElement():
"""
Creates a new (empty) :class:`ComplexDoubleElement`.
"""
cdef ComplexDoubleElement z
z = ComplexDoubleElement.__new__(ComplexDoubleElement)
return z
def is_ComplexDoubleElement(x):
"""
Return ``True`` if ``x`` is a :class:`ComplexDoubleElement`.
EXAMPLES::
sage: from sage.rings.complex_double import is_ComplexDoubleElement
sage: is_ComplexDoubleElement(0)
False
sage: is_ComplexDoubleElement(CDF(0))
True
"""
return isinstance(x, ComplexDoubleElement)
cdef inline ComplexDoubleElement pari_to_cdf(pari_gen g):
"""
Create a CDF element from a PARI ``gen``.
EXAMPLES::
sage: CDF(pari("Pi"))
3.141592653589793
sage: CDF(pari("1 + I/2"))
1.0 + 0.5*I
TESTS:
Check that we handle PARI errors gracefully, see :trac:`17329`::
sage: CDF(-151.386325246 + 992.34771962*I).zeta()
Traceback (most recent call last):
...
PariError: overflow in t_REAL->double conversion
sage: CDF(pari(x^2 + 5))
Traceback (most recent call last):
...
PariError: incorrect type in gtofp (t_POL)
"""
cdef ComplexDoubleElement z = ComplexDoubleElement.__new__(ComplexDoubleElement)
sig_on()
if typ(g.g) == t_COMPLEX:
z._complex = gsl_complex_rect(gtodouble(gel(g.g, 1)), gtodouble(gel(g.g, 2)))
else:
z._complex = gsl_complex_rect(gtodouble(g.g), 0.0)
sig_off()
return z
cdef class ComplexDoubleElement(FieldElement):
"""
An approximation to a complex number using double precision
floating point numbers. Answers derived from calculations with such
approximations may differ from what they would be if those
calculations were performed with true complex numbers. This is due
to the rounding errors inherent to finite precision calculations.
"""
__array_interface__ = {'typestr': '=c16'}
def __cinit__(self):
r"""
Initialize ``self`` as an element of `\CC`.
EXAMPLES::
sage: ComplexDoubleElement(1,-2) # indirect doctest
1.0 - 2.0*I
"""
self._parent = _CDF
def __init__(self, real, imag):
"""
Constructs an element of a complex double field with specified real
and imaginary values.
EXAMPLES::
sage: ComplexDoubleElement(1,-2)
1.0 - 2.0*I
"""
self._complex = gsl_complex_rect(real, imag)
def __reduce__(self):
"""
For pickling.
EXAMPLES::
sage: a = CDF(-2.7, -3)
sage: loads(dumps(a)) == a
True
"""
return (ComplexDoubleElement,
(self._complex.real, self._complex.imag))
cdef ComplexDoubleElement _new_c(self, gsl_complex x):
"""
C-level code for creating a :class:`ComplexDoubleElement` from a
``gsl_complex``.
"""
cdef ComplexDoubleElement z = <ComplexDoubleElement>ComplexDoubleElement.__new__(ComplexDoubleElement)
z._complex = x
return z
def __hash__(self):
"""
Returns the hash of ``self``, which coincides with the python ``float``
and ``complex`` (and often ``int``) types for ``self``.
EXAMPLES::
sage: hash(CDF(1.2)) == hash(1.2r)
True
sage: hash(CDF(-1))
-2
sage: hash(CDF(1.2, 1.3)) == hash(complex(1.2r, 1.3r))
True
"""
return hash(complex(self))
cpdef int _cmp_(left, right) except -2:
"""
We order the complex numbers in dictionary order by real parts then
imaginary parts.
This order, of course, does not respect the field structure, though
it agrees with the usual order on the real numbers.
EXAMPLES::
sage: CDF(1.2) > CDF(i)
True
sage: CDF(1) < CDF(2)
True
sage: CDF(1 + i) > CDF(-1 - i)
True
::
sage: CDF(2,3) < CDF(3,1)
True
sage: CDF(2,3) > CDF(3,1)
False
sage: CDF(2,-1) < CDF(2,3)
True
It's dictionary order, not absolute value::
sage: CDF(-1,3) < CDF(-1,-20)
False
Numbers are coerced before comparison::
sage: CDF(3,5) < 7
True
sage: 4.3 > CDF(5,1)
False
"""
if left._complex.real < (<ComplexDoubleElement>right)._complex.real:
return -1
if left._complex.real > (<ComplexDoubleElement>right)._complex.real:
return 1
if left._complex.imag < (<ComplexDoubleElement>right)._complex.imag:
return -1
if left._complex.imag > (<ComplexDoubleElement>right)._complex.imag:
return 1
return 0
def __getitem__(self, n):
"""
Returns the real or imaginary part of ``self``.
INPUT:
- ``n`` -- integer (either 0 or 1)
Raises an ``IndexError`` if ``n`` is not 0 or 1.
EXAMPLES::
sage: P = CDF(2,3)
sage: P[0]
2.0
sage: P[1]
3.0
sage: P[3]
Traceback (most recent call last):
...
IndexError: index n must be 0 or 1
"""
if n >= 0 and n <= 1:
return self._complex.dat[n]
raise IndexError("index n must be 0 or 1")
def _magma_init_(self, magma):
r"""
Return the magma representation of ``self``.
EXAMPLES::
sage: CDF((1.2, 0.3))._magma_init_(magma) # optional - magma
'ComplexField(53 : Bits := true)![1.2, 0.3]'
sage: magma(CDF(1.2, 0.3)) # optional - magma # indirect doctest
1.20000000000000 + 0.300000000000000*$.1
sage: s = magma(CDF(1.2, 0.3)).sage(); s # optional - magma # indirect doctest
1.20000000000000 + 0.300000000000000*I
sage: s.parent() # optional - magma
Complex Field with 53 bits of precision
"""
return "%s![%s, %s]" % (self.parent()._magma_init_(magma), self.real(), self.imag())
def prec(self):
"""
Returns the precision of this number (to be more similar to
:class:`ComplexNumber`). Always returns 53.
EXAMPLES::
sage: CDF(0).prec()
53
"""
return 53
#######################################################################
# Coercions
#######################################################################
def __int__(self):
"""
Convert ``self`` to an ``int``.
EXAMPLES::
sage: int(CDF(1,1))
Traceback (most recent call last):
...
TypeError: can't convert complex to int; use int(abs(z))
sage: int(abs(CDF(1,1)))
1
"""
raise TypeError("can't convert complex to int; use int(abs(z))")
def __long__(self):
"""
Convert ``self`` to a ``long``.
EXAMPLES::
sage: long(CDF(1,1)) # py2
Traceback (most recent call last):
...
TypeError: can't convert complex to long; use long(abs(z))
sage: long(abs(CDF(1,1)))
1L
"""
raise TypeError("can't convert complex to long; use long(abs(z))")
def __float__(self):
"""
Method for converting ``self`` to type ``float``. Called by the
``float`` function. This conversion will throw an error if
the number has a nonzero imaginary part.
EXAMPLES::
sage: a = CDF(1, 0)
sage: float(a)
1.0
sage: a = CDF(2,1)
sage: float(a)
Traceback (most recent call last):
...
TypeError: unable to convert 2.0 + 1.0*I to float; use abs() or real_part() as desired
sage: a.__float__()
Traceback (most recent call last):
...
TypeError: unable to convert 2.0 + 1.0*I to float; use abs() or real_part() as desired
sage: float(abs(CDF(1,1)))
1.4142135623730951
"""
if self._complex.imag:
raise TypeError(f"unable to convert {self} to float; use abs() or real_part() as desired")
return self._complex.real
def __complex__(self):
"""
Convert ``self`` to python's ``complex`` object.
EXAMPLES::
sage: a = complex(2303,-3939)
sage: CDF(a)
2303.0 - 3939.0*I
sage: complex(CDF(a))
(2303-3939j)
"""
return complex(self._complex.real, self._complex.imag)
def _interface_init_(self, I=None):
"""
Returns ``self`` formatted as a string, suitable as input to another
computer algebra system. (This is the default function used for
exporting to other computer algebra systems.)
EXAMPLES::
sage: s1 = CDF(exp(I)); s1
0.5403023058681398 + 0.8414709848078965*I
sage: s1._interface_init_()
'0.54030230586813977 + 0.84147098480789650*I'
sage: s1 == CDF(gp(s1))