This repository has been archived by the owner on Jan 30, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
complex_mpc.pyx
2575 lines (2071 loc) · 76.9 KB
/
complex_mpc.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
"""
Arbitrary Precision Complex Numbers using GNU MPC
This is a binding for the MPC arbitrary-precision floating point library.
It is adaptated from ``real_mpfr.pyx`` and ``complex_number.pyx``.
We define a class :class:`MPComplexField`, where each instance of
``MPComplexField`` specifies a field of floating-point complex numbers with
a specified precision shared by the real and imaginary part and a rounding
mode stating the rounding mode directions specific to real and imaginary
parts.
Individual floating-point numbers are of class :class:`MPComplexNumber`.
For floating-point representation and rounding mode description see the
documentation for the :mod:`sage.rings.real_mpfr`.
AUTHORS:
- Philippe Theveny (2008-10-13): initial version.
- Alex Ghitza (2008-11): cache, generators, random element, and many doctests.
- Yann Laigle-Chapuy (2010-01): improves compatibility with CC, updates.
- Jeroen Demeyer (2012-02): reformat documentation, make MPC a standard
package.
- Travis Scrimshaw (2012-10-18): Added doctests for full coverage.
- Vincent Klein (2017-11-15) : add __mpc__() to class MPComplexNumber.
MPComplexNumber constructor support gmpy2.mpz, gmpy2.mpq, gmpy2.mpfr
and gmpy2.mpc parameters.
EXAMPLES::
sage: MPC = MPComplexField(42)
sage: a = MPC(12, '15.64E+32'); a
12.0000000000 + 1.56400000000e33*I
sage: a *a *a *a
5.98338564121e132 - 1.83633318912e101*I
sage: a + 1
13.0000000000 + 1.56400000000e33*I
sage: a / 3
4.00000000000 + 5.21333333333e32*I
sage: MPC("infinity + NaN *I")
+infinity + NaN*I
"""
# ****************************************************************************
# Copyright (C) 2008 Philippe Theveny <thevenyp@loria.fr>
# 2008 Alex Ghitza
# 2010 Yann Laigle-Chapuy
# 2012 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/
# ****************************************************************************
import re
from . import real_mpfr
import weakref
from cpython.object cimport Py_NE
import sage
from sage.cpython.string cimport str_to_bytes
from sage.libs.mpfr cimport *
from sage.libs.mpc cimport *
from sage.structure.parent cimport Parent
from sage.structure.parent_gens cimport ParentWithGens
from sage.structure.element cimport RingElement, Element, ModuleElement
from sage.structure.richcmp cimport rich_to_bool
from sage.categories.map cimport Map
from sage.libs.pari.all import pari
from .integer cimport Integer
from .complex_number cimport ComplexNumber
from .complex_field import ComplexField_class
from sage.misc.randstate cimport randstate, current_randstate
from .real_mpfr cimport RealField_class, RealNumber
from .real_mpfr import mpfr_prec_min, mpfr_prec_max
from sage.structure.richcmp cimport rich_to_bool, richcmp
from sage.categories.fields import Fields
cimport gmpy2
gmpy2.import_gmpy2()
NumberFieldElement_quadratic = None
AlgebraicNumber_base = None
AlgebraicNumber = None
AlgebraicReal = None
AA = None
QQbar = None
CDF = CLF = RLF = None
def late_import():
"""
Import the objects/modules after build (when needed).
TESTS::
sage: sage.rings.complex_mpc.late_import()
"""
global NumberFieldElement_quadratic
global AlgebraicNumber_base
global AlgebraicNumber
global AlgebraicReal
global AA, QQbar
global CLF, RLF, CDF
if NumberFieldElement_quadratic is None:
import sage.rings.number_field.number_field_element_quadratic as nfeq
NumberFieldElement_quadratic = nfeq.NumberFieldElement_quadratic
import sage.rings.qqbar
AlgebraicNumber_base = sage.rings.qqbar.AlgebraicNumber_base
AlgebraicNumber = sage.rings.qqbar.AlgebraicNumber
AlgebraicReal = sage.rings.qqbar.AlgebraicReal
AA = sage.rings.qqbar.AA
QQbar = sage.rings.qqbar.QQbar
from .real_lazy import CLF, RLF
from .complex_double import CDF
_mpfr_rounding_modes = ['RNDN', 'RNDZ', 'RNDU', 'RNDD']
_mpc_rounding_modes = [ 'RNDNN', 'RNDZN', 'RNDUN', 'RNDDN',
'', '', '', '', '', '', '', '', '', '', '', '',
'RNDNZ', 'RNDZZ', 'RNDUZ', 'RNDDZ',
'', '', '', '', '', '', '', '', '', '', '', '',
'RNDUN', 'RNDZU', 'RNDUU', 'RNDDU',
'', '', '', '', '', '', '', '', '', '', '', '',
'RNDDN', 'RNDZD', 'RNDUD', 'RNDDD' ]
cdef inline mpfr_rnd_t rnd_re(mpc_rnd_t rnd):
"""
Return the numeric value of the real part rounding mode. This
is an internal function.
"""
return <mpfr_rnd_t>(rnd & 3)
cdef inline mpfr_rnd_t rnd_im(mpc_rnd_t rnd):
"""
Return the numeric value of the imaginary part rounding mode.
This is an internal function.
"""
return <mpfr_rnd_t>(rnd >> 4)
sign = '[+-]'
digit_ten = '[0123456789]'
exponent_ten = '[e@]' + sign + '?[0123456789]+'
number_ten = 'inf(?:inity)?|@inf@|nan(?:\([0-9A-Z_]*\))?|@nan@(?:\([0-9A-Z_]*\))?'\
'|(?:' + digit_ten + '*\.' + digit_ten + '+|' + digit_ten + '+\.?)(?:' + exponent_ten + ')?'
imaginary_ten = 'i(?:\s*\*\s*(?:' + number_ten + '))?|(?:' + number_ten + ')\s*\*\s*i'
complex_ten = '(?P<im_first>(?P<im_first_im_sign>' + sign + ')?\s*(?P<im_first_im_abs>' + imaginary_ten + ')' \
'(\s*(?P<im_first_re_sign>' + sign + ')\s*(?P<im_first_re_abs>' + number_ten + '))?)' \
'|' \
'(?P<re_first>(?P<re_first_re_sign>' + sign + ')?\s*(?P<re_first_re_abs>' + number_ten + ')' \
'(\s*(?P<re_first_im_sign>' + sign + ')\s*(?P<re_first_im_abs>' + imaginary_ten + '))?)'
re_complex_ten = re.compile('^\s*(?:' + complex_ten + ')\s*$', re.I)
cpdef inline split_complex_string(string, int base=10):
"""
Split and return in that order the real and imaginary parts
of a complex in a string.
This is an internal function.
EXAMPLES::
sage: sage.rings.complex_mpc.split_complex_string('123.456e789')
('123.456e789', None)
sage: sage.rings.complex_mpc.split_complex_string('123.456e789*I')
(None, '123.456e789')
sage: sage.rings.complex_mpc.split_complex_string('123.+456e789*I')
('123.', '+456e789')
sage: sage.rings.complex_mpc.split_complex_string('123.456e789', base=2)
(None, None)
"""
if base == 10:
number = number_ten
z = re_complex_ten.match(string)
else:
all_digits = "0123456789abcdefghijklmnopqrstuvwxyz"
digit = '[' + all_digits[0:base] + ']'
# In MPFR, '1e42'-> 10^42, '1p42'->2^42, '1@42'->base^42
if base == 2:
exponent = '[e@p]'
elif base <= 10:
exponent = '[e@]'
elif base == 16:
exponent = '[@p]'
else:
exponent = '@'
exponent += sign + '?' + digit + '+'
# Warning: number, imaginary, and complex should be enclosed in parentheses
# when used as regexp because of alternatives '|'
number = '@nan@(?:\([0-9A-Z_]*\))?|@inf@|(?:' + digit + '*\.' + digit + '+|' + digit + '+\.?)(?:' + exponent + ')?'
if base <= 10:
number = 'nan(?:\([0-9A-Z_]*\))?|inf(?:inity)?|' + number
imaginary = 'i(?:\s*\*\s*(?:' + number + '))?|(?:' + number + ')\s*\*\s*i'
complex = '(?P<im_first>(?P<im_first_im_sign>' + sign + ')?\s*(?P<im_first_im_abs>' + imaginary + ')' \
'(\s*(?P<im_first_re_sign>' + sign + ')\s*(?P<im_first_re_abs>' + number + '))?)' \
'|' \
'(?P<re_first>(?P<re_first_re_sign>' + sign + ')?\s*(?P<re_first_re_abs>' + number + ')' \
'(\s*(?P<re_first_im_sign>' + sign + ')\s*(?P<re_first_im_abs>' + imaginary + '))?)'
z = re.match('^\s*(?:' + complex + ')\s*$', string, re.I)
x, y = None, None
if z is not None:
if z.group('im_first') is not None:
prefix = 'im_first'
elif z.group('re_first') is not None:
prefix = 're_first'
else:
return None
if z.group(prefix + '_re_abs') is not None:
x = z.expand('\g<' + prefix + '_re_abs>')
if z.group(prefix + '_re_sign') is not None:
x = z.expand('\g<' + prefix + '_re_sign>') + x
if z.group(prefix + '_im_abs') is not None:
y = re.search('(?P<im_part>' + number + ')', z.expand('\g<' + prefix + '_im_abs>'), re.I)
if y is None:
y = '1'
else:
y = y.expand('\g<im_part>')
if z.group(prefix + '_im_sign') is not None:
y = z.expand('\g<' + prefix + '_im_sign>') + y
return x, y
#*****************************************************************************
#
# MPComplex Field
#
#*****************************************************************************
# The complex field is in Cython, so mpc elements will have access to
# their parent via direct C calls, which will be faster.
cache = {}
def MPComplexField(prec=53, rnd="RNDNN", names=None):
"""
Return the complex field with real and imaginary parts having
prec *bits* of precision.
EXAMPLES::
sage: MPComplexField()
Complex Field with 53 bits of precision
sage: MPComplexField(100)
Complex Field with 100 bits of precision
sage: MPComplexField(100).base_ring()
Real Field with 100 bits of precision
sage: i = MPComplexField(200).gen()
sage: i^2
-1.0000000000000000000000000000000000000000000000000000000000
"""
global cache
mykey = (prec, rnd)
if mykey in cache:
X = cache[mykey]
C = X()
if not C is None:
return C
C = MPComplexField_class(prec, rnd)
cache[mykey] = weakref.ref(C)
return C
cdef class MPComplexField_class(sage.rings.ring.Field):
def __init__(self, int prec=53, rnd="RNDNN"):
"""
Initialize ``self``.
INPUT:
- ``prec`` -- (integer) precision; default = 53
prec is the number of bits used to represent the mantissa of
both the real and imaginary part of complex floating-point number.
- ``rnd`` -- (string) the rounding mode; default = ``'RNDNN'``
Rounding mode is of the form ``'RNDxy'`` where ``x`` and ``y`` are
the rounding mode for respectively the real and imaginary parts and
are one of:
- ``'N'`` for rounding to nearest
- ``'Z'`` for rounding towards zero
- ``'U'`` for rounding towards plus infinity
- ``'D'`` for rounding towards minus infinity
For example, ``'RNDZU'`` indicates to round the real part towards
zero, and the imaginary part towards plus infinity.
EXAMPLES::
sage: MPComplexField(17)
Complex Field with 17 bits of precision
sage: MPComplexField()
Complex Field with 53 bits of precision
sage: MPComplexField(1042,'RNDDZ')
Complex Field with 1042 bits of precision and rounding RNDDZ
ALGORITHMS: Computations are done using the MPC library.
TESTS::
sage: TestSuite(MPComplexField(17)).run()
sage: MPComplexField(17).is_finite()
False
"""
if prec < mpfr_prec_min() or prec > mpfr_prec_max():
raise ValueError("prec (=%s) must be >= %s and <= %s." % (
prec, mpfr_prec_min(), mpfr_prec_max()))
self.__prec = prec
if not isinstance(rnd, str):
raise TypeError("rnd must be a string")
try:
n = _mpc_rounding_modes.index(rnd)
except ValueError:
raise ValueError("rnd (=%s) must be of the form RNDxy"\
"where x and y are one of N, Z, U, D" % rnd)
self.__rnd = n
self.__rnd_str = rnd
self.__real_field = real_mpfr.RealField(prec, rnd=_mpfr_rounding_modes[rnd_re(n)])
self.__imag_field = real_mpfr.RealField(prec, rnd=_mpfr_rounding_modes[rnd_im(n)])
ParentWithGens.__init__(self, self._real_field(), ('I',), False, category=Fields().Infinite())
self._populate_coercion_lists_(coerce_list=[MPFRtoMPC(self._real_field(), self)])
cdef MPComplexNumber _new(self):
"""
Return a new complex number with parent ``self`.
"""
cdef MPComplexNumber z
z = MPComplexNumber.__new__(MPComplexNumber)
z._parent = self
mpc_init2(z.value, self.__prec)
z.init = 1
return z
def _repr_ (self):
"""
Return a string representation of ``self``.
EXAMPLES::
sage: MPComplexField(200, 'RNDDU') # indirect doctest
Complex Field with 200 bits of precision and rounding RNDDU
"""
s = "Complex Field with %s bits of precision"%self.__prec
if self.__rnd != MPC_RNDNN:
s = s + " and rounding %s"%(self.__rnd_str)
return s
def _latex_(self):
r"""
Return a latex representation of ``self``.
EXAMPLES::
sage: MPC = MPComplexField(10)
sage: latex(MPC) # indirect doctest
\C
"""
return "\\C"
def __call__(self, x, im=None):
"""
Create a floating-point complex using ``x`` and optionally an imaginary
part ``im``.
EXAMPLES::
sage: MPC = MPComplexField()
sage: MPC(2) # indirect doctest
2.00000000000000
sage: MPC(0, 1) # indirect doctest
1.00000000000000*I
sage: MPC(1, 1)
1.00000000000000 + 1.00000000000000*I
sage: MPC(2, 3)
2.00000000000000 + 3.00000000000000*I
"""
if x is None:
return self.zero()
# 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, z):
"""
Coerce `z` into this complex field.
EXAMPLES::
sage: C20 = MPComplexField(20) # indirect doctest
The value can be set with a couple of reals::
sage: a = C20(1.5625, 17.42); a
1.5625 + 17.420*I
sage: a.str(2)
'1.1001000000000000000 + 10001.011010111000011*I'
sage: C20(0, 2)
2.0000*I
Complex number can be coerced into MPComplexNumber::
sage: C20(14.7+0.35*I)
14.700 + 0.35000*I
sage: C20(i*4, 7)
Traceback (most recent call last):
...
TypeError: unable to coerce to a ComplexNumber: <type 'sage.symbolic.expression.Expression'>
Each part can be set with strings (written in base ten)::
sage: C20('1.234', '56.789')
1.2340 + 56.789*I
The string can represent the whole complex value::
sage: C20('42 + I * 100')
42.000 + 100.00*I
sage: C20('-42 * I')
- 42.000*I
The imaginary part can be written first::
sage: C20('100*i+42')
42.000 + 100.00*I
Use ``'inf'`` for infinity and ``'nan'`` for Not a Number::
sage: C20('nan+inf*i')
NaN + +infinity*I
"""
cdef MPComplexNumber zz
zz = self._new()
zz._set(z)
return zz
cpdef _coerce_map_from_(self, S):
"""
Canonical coercion of `z` to this mpc complex field.
The rings that canonically coerce to this mpc complex field are:
- any mpc complex field with precision that is as large as this one
- anything that canonically coerces to the mpfr real
field with this prec and the rounding mode of real part.
EXAMPLES::
sage: MPComplexField(100)(17, '4.2') + MPComplexField(20)('6.0', -23) # indirect doctest
23.000 - 18.800*I
sage: a = MPComplexField(100)(17, '4.2') + MPComplexField(20)('6.0', -23)
sage: a.parent()
Complex Field with 20 bits of precision
"""
if isinstance(S, RealField_class):
return MPFRtoMPC(S, self)
if isinstance(S, sage.rings.integer_ring.IntegerRing_class):
return INTEGERtoMPC(S, self)
RR = self.__real_field
if RR.has_coerce_map_from(S):
return self._coerce_map_via([RR], S)
if isinstance(S, MPComplexField_class) and S.prec() >= self.__prec:
#FIXME: What map when rounding modes differ but prec is the same ?
# How to provide commutativity of morphisms ?
# Change _cmp_ when done
return MPCtoMPC(S, self)
if isinstance(S, ComplexField_class) and S.prec() >= self.__prec:
return CCtoMPC(S, self)
late_import()
if S in [AA, QQbar, CLF, RLF] or (S == CDF and self._prec <= 53):
return self._generic_coerce_map(S)
return self._coerce_map_via([CLF], S)
def __reduce__(self):
"""
For pickling.
EXAMPLES::
sage: C = MPComplexField(prec=200, rnd='RNDDZ')
sage: loads(dumps(C)) == C
True
"""
return __create__MPComplexField_version0, (self.__prec, self.__rnd_str)
def __richcmp__(left, right, int op):
"""
Compare ``self`` and ``other``, ignoring the rounding mode.
EXAMPLES::
sage: MPComplexField(10) == MPComplexField(11) # indirect doctest
False
sage: MPComplexField(10) == MPComplexField(10)
True
sage: MPComplexField(10,rnd='RNDZN') == MPComplexField(10,rnd='RNDZU')
True
"""
if left is right:
return rich_to_bool(op, 0)
if not isinstance(right, MPComplexField_class):
return op == Py_NE
cdef MPComplexField_class s = <MPComplexField_class>left
cdef MPComplexField_class o = <MPComplexField_class>right
return richcmp(s.__prec, o.__prec, op)
def gen(self, n=0):
"""
Return the generator of this complex field over its real subfield.
EXAMPLES::
sage: MPComplexField(34).gen()
1.00000000*I
"""
if n != 0:
raise IndexError("n must be 0")
return self(0, 1)
def ngens(self):
"""
Return 1, the number of generators of this complex field over its real
subfield.
EXAMPLES::
sage: MPComplexField(34).ngens()
1
"""
return 1
cpdef _an_element_(self):
"""
Return an element of this complex field.
EXAMPLES::
sage: MPC = MPComplexField(20)
sage: MPC._an_element_()
1.0000*I
"""
return self(0, 1)
def random_element(self, min=0, max=1):
"""
Return a random complex number, uniformly distributed with
real and imaginary parts between min and max (default 0 to 1).
EXAMPLES::
sage: MPComplexField(100).random_element(-5, 10) # random
1.9305310520925994224072377281 + 0.94745292506956219710477444855*I
sage: MPComplexField(10).random_element() # random
0.12 + 0.23*I
"""
cdef MPComplexNumber z
z = self._new()
cdef randstate rstate = current_randstate()
mpc_urandom(z.value, rstate.gmp_state)
if min == 0 and max == 1:
return z
else:
return (max-min)*z + min*self(1,1)
cpdef bint is_exact(self) except -2:
"""
Returns whether or not this field is exact, which is always ``False``.
EXAMPLES::
sage: MPComplexField(42).is_exact()
False
"""
return False
def characteristic(self):
"""
Return 0, since the field of complex numbers has characteristic 0.
EXAMPLES::
sage: MPComplexField(42).characteristic()
0
"""
return Integer(0)
def name(self):
"""
Return the name of the complex field.
EXAMPLES::
sage: C = MPComplexField(10, 'RNDNZ'); C.name()
'MPComplexField10_RNDNZ'
"""
return "MPComplexField%s_%s"%(self.__prec, self.__rnd_str)
def __hash__(self):
"""
Return the hash of ``self``.
EXAMPLES::
sage: MPC = MPComplexField()
sage: hash(MPC) % 2^32 == hash(MPC.name()) % 2^32
True
"""
return hash(self.name())
def prec(self):
"""
Return the precision of this field of complex numbers.
EXAMPLES::
sage: MPComplexField().prec()
53
sage: MPComplexField(22).prec()
22
"""
return self.__prec
def rounding_mode(self):
"""
Return rounding modes used for each part of a complex number.
EXAMPLES::
sage: MPComplexField().rounding_mode()
'RNDNN'
sage: MPComplexField(rnd='RNDZU').rounding_mode()
'RNDZU'
"""
return self.__rnd_str
def rounding_mode_real(self):
"""
Return rounding mode used for the real part of complex number.
EXAMPLES::
sage: MPComplexField(rnd='RNDZU').rounding_mode_real()
'RNDZ'
"""
return _mpfr_rounding_modes[rnd_re(self.__rnd)]
def rounding_mode_imag(self):
"""
Return rounding mode used for the imaginary part of complex number.
EXAMPLES::
sage: MPComplexField(rnd='RNDZU').rounding_mode_imag()
'RNDU'
"""
return _mpfr_rounding_modes[rnd_im(self.__rnd)]
def _real_field(self):
"""
Return real field for the real part.
EXAMPLES::
sage: MPComplexField()._real_field()
Real Field with 53 bits of precision
"""
return self.__real_field
def _imag_field(self):
"""
Return real field for the imaginary part.
EXAMPLES::
sage: MPComplexField(prec=100)._imag_field()
Real Field with 100 bits of precision
"""
return self.__imag_field
#*****************************************************************************
#
# MPComplex Number -- element of MPComplex Field
#
#*****************************************************************************
cdef class MPComplexNumber(sage.structure.element.FieldElement):
"""
A floating point approximation to a complex number using any specified
precision common to both real and imaginary part.
"""
cdef MPComplexNumber _new(self):
"""
Return a new complex number with same parent as ``self``.
"""
cdef MPComplexNumber z
z = MPComplexNumber.__new__(MPComplexNumber)
z._parent = self._parent
mpc_init2(z.value, (<MPComplexField_class>self._parent).__prec)
z.init = 1
return z
def __init__(self, MPComplexField_class parent, x, y=None, int base=10):
"""
Create a complex number.
INPUT:
- ``x`` -- real part or the complex value in a string
- ``y`` -- imaginary part
- ``base`` -- when ``x`` or ``y`` is a string, base in which the
number is written
A :class:`MPComplexNumber` should be called by first creating a
:class:`MPComplexField`, as illustrated in the examples.
EXAMPLES::
sage: C200 = MPComplexField(200)
sage: C200(1/3, '0.6789')
0.33333333333333333333333333333333333333333333333333333333333 + 0.67890000000000000000000000000000000000000000000000000000000*I
sage: C3 = MPComplexField(3)
sage: C3('1.2345', '0.6789')
1.2 + 0.62*I
sage: C3(3.14159)
3.0
Rounding modes::
sage: w = C3(5/2, 7/2); w.str(2)
'10.1 + 11.1*I'
sage: MPComplexField(2, rnd="RNDZN")(w).str(2)
'10. + 100.*I'
sage: MPComplexField(2, rnd="RNDDU")(w).str(2)
'10. + 100.*I'
sage: MPComplexField(2, rnd="RNDUD")(w).str(2)
'11. + 11.*I'
sage: MPComplexField(2, rnd="RNDNZ")(w).str(2)
'10. + 11.*I'
TESTS::
sage: MPComplexField(42)._repr_option('element_is_atomic')
False
"""
self.init = 0
if parent is None:
raise TypeError
self._parent = parent
mpc_init2(self.value, parent.__prec)
self.init = 1
if x is None: return
self._set(x, y, base)
def _set(self, z, y=None, base=10):
"""
EXAMPLES::
sage: MPC = MPComplexField(100)
sage: r = RealField(100).pi()
sage: z = MPC(r); z # indirect doctest
3.1415926535897932384626433833
sage: MPComplexField(10, rnd='RNDDD')(z)
3.1
sage: c = ComplexField(53)(1, r)
sage: MPC(c)
1.0000000000000000000000000000 + 3.1415926535897931159979634685*I
sage: MPC(I)
1.0000000000000000000000000000*I
sage: MPC('-0 +i')
1.0000000000000000000000000000*I
sage: MPC(1+i)
1.0000000000000000000000000000 + 1.0000000000000000000000000000*I
sage: MPC(1/3)
0.33333333333333333333333333333
::
sage: MPC(1, r/3)
1.0000000000000000000000000000 + 1.0471975511965977461542144611*I
sage: MPC(3, 2)
3.0000000000000000000000000000 + 2.0000000000000000000000000000*I
sage: MPC(0, r)
3.1415926535897932384626433833*I
sage: MPC('0.625e-26', '0.0000001')
6.2500000000000000000000000000e-27 + 1.0000000000000000000000000000e-7*I
Conversion from gmpy2 numbers::
sage: from gmpy2 import *
sage: MPC(mpc(int(2),int(1)))
2.0000000000000000000000000000 + 1.0000000000000000000000000000*I
sage: MPC(mpfr(2.5))
2.5000000000000000000000000000
sage: MPC(mpq('3/2'))
1.5000000000000000000000000000
sage: MPC(mpz(int(5)))
5.0000000000000000000000000000
sage: re = mpfr('2.5')
sage: im = mpz(int(2))
sage: MPC(re, im)
2.5000000000000000000000000000 + 2.0000000000000000000000000000*I
"""
# This should not be called except when the number is being created.
# Complex Numbers are supposed to be immutable.
cdef RealNumber x
cdef mpc_rnd_t rnd
rnd =(<MPComplexField_class>self._parent).__rnd
if y is None:
if z is None: return
if isinstance(z, MPComplexNumber):
mpc_set(self.value, (<MPComplexNumber>z).value, rnd)
return
elif isinstance(z, str):
a, b = split_complex_string(z, base)
# set real part
if a is None:
mpfr_set_ui(self.value.re, 0, MPFR_RNDN)
else:
mpfr_set_str(self.value.re, str_to_bytes(a),
base, rnd_re(rnd))
# set imag part
if b is None:
if a is None:
raise TypeError("unable to convert {!r} to a MPComplexNumber".format(z))
else:
mpfr_set_str(self.value.im, str_to_bytes(b),
base, rnd_im(rnd))
return
elif isinstance(z, ComplexNumber):
mpc_set_fr_fr(self.value, (<ComplexNumber>z).__re, (<ComplexNumber>z).__im, rnd)
return
elif isinstance(z, sage.libs.pari.all.pari_gen):
real, imag = z.real(), z.imag()
elif isinstance(z, list) or isinstance(z, tuple):
real, imag = z
elif isinstance(z, complex):
real, imag = z.real, z.imag
elif isinstance(z, sage.symbolic.expression.Expression):
zz = sage.rings.complex_field.ComplexField(self._parent.prec())(z)
self._set(zz)
return
elif type(z) is gmpy2.mpc:
mpc_set(self.value, (<gmpy2.mpc>z).c, rnd)
return
# then, no imaginary part
elif type(z) is gmpy2.mpfr:
mpc_set_fr(self.value, (<gmpy2.mpfr>z).f, rnd)
return
elif type(z) is gmpy2.mpq:
mpc_set_q(self.value, (<gmpy2.mpq>z).q, rnd)
return
elif type(z) is gmpy2.mpz:
mpc_set_z(self.value, (<gmpy2.mpz>z).z, rnd)
return
elif isinstance(z, RealNumber):
zz = sage.rings.real_mpfr.RealField(self._parent.prec())(z)
mpc_set_fr(self.value, (<RealNumber>zz).value, rnd)
return
elif isinstance(z, Integer):
mpc_set_z(self.value, (<Integer>z).value, rnd)
return
elif isinstance(z, (int, long)):
mpc_set_si(self.value, z, rnd)
return
else:
real = z
imag = 0
else:
real = z
imag = y
cdef RealField_class R = self._parent._real_field()
try:
rr = R(real)
ii = R(imag)
mpc_set_fr_fr(self.value, (<RealNumber>rr).value, (<RealNumber>ii).value, rnd)
except TypeError:
raise TypeError("unable to coerce to a ComplexNumber: %s" % type(real))
def __reduce__(self):
"""
For pickling.
EXAMPLES::
sage: C = MPComplexField(prec=200, rnd='RNDUU')
sage: b = C(393.39203845902384098234098230948209384028340)
sage: loads(dumps(b)) == b
True
sage: b = C(-1).sqrt(); b
1.0000000000000000000000000000000000000000000000000000000000*I
sage: loads(dumps(b)) == b
True
Some tests with ``NaN``, which cannot be compared to anything::
sage: b = C(1)/C(0); b
NaN + NaN*I
sage: loads(dumps(b))
NaN + NaN*I
sage: b = C(-1)/C(0.); b
NaN + NaN*I
sage: loads(dumps(b))
NaN + NaN*I
"""
s = self.str(32)
return (__create_MPComplexNumber_version0, (self._parent, s, 32))
def __dealloc__(self):
if self.init:
mpc_clear(self.value)
def _repr_(self):
"""
Return a string representation of ``self``.
EXAMPLES::
sage: MPComplexField()(2, -3) # indirect doctest
2.00000000000000 - 3.00000000000000*I
"""
return self.str(truncate=True)
def _latex_(self):
"""
Return a latex representation of ``self``.
EXAMPLES::
sage: latex(MPComplexField()(2, -3)) # indirect doctest
2.00000000000000 - 3.00000000000000i
"""
import re
s = repr(self).replace('*I', 'i')
return re.sub(r"e(-?\d+)", r" \\times 10^{\1}", s)
def __hash__(self):
"""
Returns the hash of ``self``, which coincides with the python
complex and float (and often int) types.
This has the drawback that two very close high precision
numbers will have the same hash, but allows them to play
nicely with other real types.
EXAMPLES::
sage: hash(MPComplexField()('1.2', 33)) == hash(complex(1.2, 33))
True
"""
return hash(complex(self))
def __getitem__(self, i):
r"""
Returns either the real or imaginary component of ``self``
depending on the choice of ``i``: real (``i``=0), imaginary (``i``=1).
INPUT:
- ``i`` -- 0 or 1
- ``0`` -- will return the real component of ``self``
- ``1`` -- will return the imaginary component of ``self``
EXAMPLES::
sage: MPC = MPComplexField()
sage: a = MPC(2,1)
sage: a.__getitem__(0)
2.00000000000000
sage: a.__getitem__(1)
1.00000000000000
::