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