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_interval.pyx
1826 lines (1465 loc) · 58.7 KB
/
complex_interval.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 Intervals
This is a simple complex interval package, using intervals which are
axis-aligned rectangles in the complex plane. It has very few special
functions, and it does not use any special tricks to keep the size of
the intervals down.
AUTHORS:
These authors wrote ``complex_number.pyx``:
- William Stein (2006-01-26): complete rewrite
- Joel B. Mohler (2006-12-16): naive rewrite into pyrex
- William Stein(2007-01): rewrite of Mohler's rewrite
Then ``complex_number.pyx`` was copied to ``complex_interval.pyx`` and
heavily modified:
- Carl Witty (2007-10-24): rewrite to become a complex interval package
- Travis Scrimshaw (2012-10-18): Added documentation to get full coverage.
.. TODO::
Implement :class:`ComplexIntervalFieldElement` multiplicative
order similar to :class:`ComplexNumber` multiplicative
order with ``_set_multiplicative_order(n)`` and
:meth:`ComplexNumber.multiplicative_order()` methods.
"""
#*****************************************************************************
# Copyright (C) 2006 William Stein <wstein@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
# http://www.gnu.org/licenses/
#*****************************************************************************
import math
import operator
include "sage/ext/interrupt.pxi"
from sage.structure.element cimport FieldElement, RingElement, Element, ModuleElement
from complex_number cimport ComplexNumber
import complex_interval_field
from complex_field import ComplexField
import sage.misc.misc
import integer
import infinity
import real_mpfi
import real_mpfr
cimport real_mpfr
cdef double LOG_TEN_TWO_PLUS_EPSILON = 3.321928094887363 # a small overestimate of log(10,2)
def is_ComplexIntervalFieldElement(x):
"""
Check if ``x`` is a :class:`ComplexIntervalFieldElement`.
EXAMPLES::
sage: from sage.rings.complex_interval import is_ComplexIntervalFieldElement as is_CIFE
sage: is_CIFE(CIF(2))
True
sage: is_CIFE(CC(2))
False
"""
return isinstance(x, ComplexIntervalFieldElement)
cdef class ComplexIntervalFieldElement(sage.structure.element.FieldElement):
"""
A complex interval.
EXAMPLES::
sage: I = CIF.gen()
sage: b = 1.5 + 2.5*I
sage: TestSuite(b).run()
"""
cdef ComplexIntervalFieldElement _new(self):
"""
Quickly creates a new initialized complex interval with the
same parent as ``self``.
"""
cdef ComplexIntervalFieldElement x
x = ComplexIntervalFieldElement.__new__(ComplexIntervalFieldElement)
x._parent = self._parent
x._prec = self._prec
mpfi_init2(x.__re, self._prec)
mpfi_init2(x.__im, self._prec)
return x
def __init__(self, parent, real, imag=None):
"""
Initialize a complex number (interval).
EXAMPLES::
sage: CIF(1.5, 2.5)
1.5000000000000000? + 2.5000000000000000?*I
sage: CIF((1.5, 2.5))
1.5000000000000000? + 2.5000000000000000?*I
sage: CIF(1.5 + 2.5*I)
1.5000000000000000? + 2.5000000000000000?*I
"""
cdef real_mpfi.RealIntervalFieldElement rr, ii
self._parent = parent
self._prec = self._parent._prec
mpfi_init2(self.__re, self._prec)
mpfi_init2(self.__im, self._prec)
if imag is None:
if isinstance(real, ComplexNumber):
real, imag = (<ComplexNumber>real).real(), (<ComplexNumber>real).imag()
elif isinstance(real, ComplexIntervalFieldElement):
real, imag = (<ComplexIntervalFieldElement>real).real(), (<ComplexIntervalFieldElement>real).imag()
elif isinstance(real, sage.libs.pari.all.pari_gen):
real, imag = real.real(), real.imag()
elif isinstance(real, list) or isinstance(real, tuple):
re, imag = real
real = re
elif isinstance(real, complex):
real, imag = real.real, real.imag
else:
imag = 0
try:
R = parent._real_field()
rr = R(real)
ii = R(imag)
mpfi_set(self.__re, rr.value)
mpfi_set(self.__im, ii.value)
except TypeError:
raise TypeError, "unable to coerce to a ComplexIntervalFieldElement"
def __dealloc__(self):
mpfi_clear(self.__re)
mpfi_clear(self.__im)
def _repr_(self):
"""
Return a string representation of ``self``.
EXAMPLES::
sage: CIF(1.5) # indirect doctest
1.5000000000000000?
sage: CIF(1.5, 2.5) # indirect doctest
1.5000000000000000? + 2.5000000000000000?*I
"""
return self.str(10)
def __hash__(self):
"""
Return the hash value of ``self``.
EXAMPLES::
sage: hash(CIF(1.5)) # indirect doctest
1517890078 # 32-bit
-3314089385045448162 # 64-bit
sage: hash(CIF(1.5, 2.5)) # indirect doctest
-1103102080 # 32-bit
3834538979630251904 # 64-bit
"""
return hash(self.str())
def __getitem__(self, i):
"""
Returns either the real or imaginary component of ``self`` depending
on the choice of ``i``: real (``i=0``), imaginary (``i=1``)
INPUTS:
- ``i`` - 0 or 1
- ``0`` -- will return the real component of ``self``
- ``1`` -- will return the imaginary component of ``self``
EXAMPLES::
sage: z = CIF(1.5, 2.5)
sage: z[0]
1.5000000000000000?
sage: z[1]
2.5000000000000000?
"""
if i == 0:
return self.real()
elif i == 1:
return self.imag()
raise IndexError, "i must be between 0 and 1."
def __reduce__( self ):
"""
Pickling support.
TESTS::
sage: a = CIF(1 + I)
sage: loads(dumps(a)) == a
True
"""
# TODO: This is potentially slow -- make a 1 version that
# is native and much faster -- doesn't use .real()/.imag()
return (make_ComplexIntervalFieldElement0, (self._parent, self.real(), self.imag()))
def str(self, base=10, style=None):
"""
Returns a string representation of ``self``.
EXAMPLES::
sage: CIF(1.5).str()
'1.5000000000000000?'
sage: CIF(1.5, 2.5).str()
'1.5000000000000000? + 2.5000000000000000?*I'
sage: CIF(1.5, -2.5).str()
'1.5000000000000000? - 2.5000000000000000?*I'
sage: CIF(0, -2.5).str()
'-2.5000000000000000?*I'
sage: CIF(1.5).str(base=3)
'1.1111111111111111111111111111111112?'
sage: CIF(1, pi).str(style='brackets')
'[1.0000000000000000 .. 1.0000000000000000] + [3.1415926535897931 .. 3.1415926535897936]*I'
.. SEEALSO::
- :meth:`RealIntervalFieldElement.str`
"""
s = ""
if not self.real().is_zero():
s = self.real().str(base=base, style=style)
if not self.imag().is_zero():
y = self.imag()
if s!="":
if y < 0:
s = s+" - "
y = -y
else:
s = s+" + "
s = s+"%s*I"%y.str(base=base, style=style)
if len(s) == 0:
s = "0"
return s
def plot(self, pointsize=10, **kwds):
r"""
Plot a complex interval as a rectangle.
EXAMPLES::
sage: sum(plot(CIF(RIF(1/k, 1/k), RIF(-k, k))) for k in [1..10])
Graphics object consisting of 20 graphics primitives
Exact and nearly exact points are still visible::
sage: plot(CIF(pi, 1), color='red') + plot(CIF(1, e), color='purple') + plot(CIF(-1, -1))
Graphics object consisting of 6 graphics primitives
A demonstration that `z \mapsto z^2` acts chaotically on `|z|=1`::
sage: z = CIF(0, 2*pi/1000).exp()
sage: g = Graphics()
sage: for i in range(40):
... z = z^2
... g += z.plot(color=(1./(40-i), 0, 1))
...
sage: g
Graphics object consisting of 80 graphics primitives
"""
from sage.plot.polygon import polygon2d
x, y = self.real(), self.imag()
x0, y0 = x.lower(), y.lower()
x1, y1 = x.upper(), y.upper()
g = polygon2d([(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)],
thickness=pointsize/4, **kwds)
# Nearly empty polygons don't show up.
g += self.center().plot(pointsize= pointsize, **kwds)
return g
def _latex_(self):
"""
Returns a latex representation of ``self``.
EXAMPLES::
sage: latex(CIF(1.5, -2.5)) # indirect doctest
1.5000000000000000? - 2.5000000000000000?i
sage: latex(CIF(0, 3e200)) # indirect doctest
3.0000000000000000? \times 10^{200}i
"""
import re
s = self.str().replace('*I', 'i')
return re.sub(r"e(-?\d+)", r" \\times 10^{\1}", s)
def bisection(self):
"""
Returns the bisection of ``self`` into four intervals whose union is
``self`` and intersection is :meth:`center()`.
EXAMPLES::
sage: z = CIF(RIF(2, 3), RIF(-5, -4))
sage: z.bisection()
(3.? - 5.?*I, 3.? - 5.?*I, 3.? - 5.?*I, 3.? - 5.?*I)
sage: for z in z.bisection():
... print z.real().endpoints(), z.imag().endpoints()
(2.00000000000000, 2.50000000000000) (-5.00000000000000, -4.50000000000000)
(2.50000000000000, 3.00000000000000) (-5.00000000000000, -4.50000000000000)
(2.00000000000000, 2.50000000000000) (-4.50000000000000, -4.00000000000000)
(2.50000000000000, 3.00000000000000) (-4.50000000000000, -4.00000000000000)
sage: z = CIF(RIF(sqrt(2), sqrt(3)), RIF(e, pi))
sage: a, b, c, d = z.bisection()
sage: a.intersection(b).intersection(c).intersection(d) == CIF(z.center())
True
sage: zz = a.union(b).union(c).union(c)
sage: zz.real().endpoints() == z.real().endpoints()
True
sage: zz.imag().endpoints() == z.imag().endpoints()
True
"""
cdef ComplexIntervalFieldElement a00 = self._new()
mpfr_set(&a00.__re.left, &self.__re.left, GMP_RNDN)
mpfi_mid(&a00.__re.right, self.__re)
mpfr_set(&a00.__im.left, &self.__im.left, GMP_RNDN)
mpfi_mid(&a00.__im.right, self.__im)
cdef ComplexIntervalFieldElement a01 = self._new()
mpfr_set(&a01.__re.left, &a00.__re.right, GMP_RNDN)
mpfr_set(&a01.__re.right, &self.__re.right, GMP_RNDN)
mpfi_set(a01.__im, a00.__im)
cdef ComplexIntervalFieldElement a10 = self._new()
mpfi_set(a10.__re, a00.__re)
mpfi_mid(&a10.__im.left, self.__im)
mpfr_set(&a10.__im.right, &self.__im.right, GMP_RNDN)
cdef ComplexIntervalFieldElement a11 = self._new()
mpfi_set(a11.__re, a01.__re)
mpfi_set(a11.__im, a10.__im)
return a00, a01, a10, a11
def is_exact(self):
"""
Returns whether this complex interval is exact (i.e. contains exactly
one complex value).
EXAMPLES::
sage: CIF(3).is_exact()
True
sage: CIF(0, 2).is_exact()
True
sage: CIF(-4, 0).sqrt().is_exact()
True
sage: CIF(-5, 0).sqrt().is_exact()
False
sage: CIF(0, 2*pi).is_exact()
False
sage: CIF(e).is_exact()
False
sage: CIF(1e100).is_exact()
True
sage: (CIF(1e100) + 1).is_exact()
False
"""
return mpfr_equal_p(&self.__re.left, &self.__re.right) and \
mpfr_equal_p(&self.__im.left, &self.__im.right)
def endpoints(self):
"""
Return the 4 corners of the rectangle in the complex plane
defined by this interval.
OUTPUT: a 4-tuple of complex numbers
(lower left, upper right, upper left, lower right)
.. SEEALSO::
:meth:`edges` which returns the 4 edges of the rectangle.
EXAMPLES::
sage: CIF(RIF(1,2), RIF(3,4)).endpoints()
(1.00000000000000 + 3.00000000000000*I,
2.00000000000000 + 4.00000000000000*I,
1.00000000000000 + 4.00000000000000*I,
2.00000000000000 + 3.00000000000000*I)
sage: ComplexIntervalField(20)(-2).log().endpoints()
(0.69315 + 3.1416*I,
0.69315 + 3.1416*I,
0.69315 + 3.1416*I,
0.69315 + 3.1416*I)
"""
left, right = self.real().endpoints()
lower, upper = self.imag().endpoints()
CC = self._parent._middle_field()
return (CC(left, lower), CC(right, upper),
CC(left, upper), CC(right, lower))
def edges(self):
"""
Return the 4 edges of the rectangle in the complex plane
defined by this interval as intervals.
OUTPUT: a 4-tuple of complex intervals
(left edge, right edge, lower edge, upper edge)
.. SEEALSO::
:meth:`endpoints` which returns the 4 corners of the
rectangle.
EXAMPLES::
sage: CIF(RIF(1,2), RIF(3,4)).edges()
(1 + 4.?*I, 2 + 4.?*I, 2.? + 3*I, 2.? + 4*I)
sage: ComplexIntervalField(20)(-2).log().edges()
(0.69314671? + 3.14160?*I,
0.69314766? + 3.14160?*I,
0.693147? + 3.1415902?*I,
0.693147? + 3.1415940?*I)
"""
cdef ComplexIntervalFieldElement left = self._new()
cdef ComplexIntervalFieldElement right = self._new()
cdef ComplexIntervalFieldElement lower = self._new()
cdef ComplexIntervalFieldElement upper = self._new()
cdef mpfr_t x
mpfr_init2(x, self.prec())
# Set real parts
mpfi_get_left(x, self.__re)
mpfi_set_fr(left.__re, x)
mpfi_get_right(x, self.__re)
mpfi_set_fr(right.__re, x)
mpfi_set(lower.__re, self.__re)
mpfi_set(upper.__re, self.__re)
# Set imaginary parts
mpfi_get_left(x, self.__im)
mpfi_set_fr(lower.__im, x)
mpfi_get_right(x, self.__im)
mpfi_set_fr(upper.__im, x)
mpfi_set(left.__im, self.__im)
mpfi_set(right.__im, self.__im)
mpfr_clear(x)
return (left, right, lower, upper)
def diameter(self):
"""
Returns a somewhat-arbitrarily defined "diameter" for this interval.
The diameter of an interval is the maximum of the diameter of the real
and imaginary components, where diameter on a real interval is defined
as absolute diameter if the interval contains zero, and relative
diameter otherwise.
EXAMPLES::
sage: CIF(RIF(-1, 1), RIF(13, 17)).diameter()
2.00000000000000
sage: CIF(RIF(-0.1, 0.1), RIF(13, 17)).diameter()
0.266666666666667
sage: CIF(RIF(-1, 1), 15).diameter()
2.00000000000000
"""
cdef real_mpfr.RealNumber diam
diam = real_mpfr.RealNumber(self._parent._real_field()._middle_field(), None)
cdef mpfr_t tmp
mpfr_init2(tmp, self.prec())
mpfi_diam(diam.value, self.__re)
mpfi_diam(tmp, self.__im)
mpfr_max(diam.value, diam.value, tmp, GMP_RNDU)
mpfr_clear(tmp)
return diam
def overlaps(self, ComplexIntervalFieldElement other):
"""
Returns ``True`` if ``self`` and other are intervals with at least
one value in common.
EXAMPLES::
sage: CIF(0).overlaps(CIF(RIF(0, 1), RIF(-1, 0)))
True
sage: CIF(1).overlaps(CIF(1, 1))
False
"""
return mpfr_greaterequal_p(&self.__re.right, &other.__re.left) \
and mpfr_greaterequal_p(&other.__re.right, &self.__re.left) \
and mpfr_greaterequal_p(&self.__im.right, &other.__im.left) \
and mpfr_greaterequal_p(&other.__im.right, &self.__im.left)
def intersection(self, other):
"""
Returns the intersection of the two complex intervals ``self`` and
``other``.
EXAMPLES::
sage: CIF(RIF(1, 3), RIF(1, 3)).intersection(CIF(RIF(2, 4), RIF(2, 4))).str(style='brackets')
'[2.0000000000000000 .. 3.0000000000000000] + [2.0000000000000000 .. 3.0000000000000000]*I'
sage: CIF(RIF(1, 2), RIF(1, 3)).intersection(CIF(RIF(3, 4), RIF(2, 4)))
Traceback (most recent call last):
...
ValueError: intersection of non-overlapping intervals
"""
cdef ComplexIntervalFieldElement x = self._new()
cdef ComplexIntervalFieldElement other_intv
if isinstance(other, ComplexIntervalFieldElement):
other_intv = other
else:
# Let type errors from _coerce_ propagate...
other_intv = self._parent(other)
mpfi_intersect(x.__re, self.__re, other_intv.__re)
mpfi_intersect(x.__im, self.__im, other_intv.__im)
if mpfr_less_p(&x.__re.right, &x.__re.left) \
or mpfr_less_p(&x.__im.right, &x.__im.left):
raise ValueError, "intersection of non-overlapping intervals"
return x
def union(self, other):
"""
Returns the smallest complex interval including the
two complex intervals ``self`` and ``other``.
EXAMPLES::
sage: CIF(0).union(CIF(5, 5)).str(style='brackets')
'[0.00000000000000000 .. 5.0000000000000000] + [0.00000000000000000 .. 5.0000000000000000]*I'
"""
cdef ComplexIntervalFieldElement x = self._new()
cdef ComplexIntervalFieldElement other_intv
if isinstance(other, ComplexIntervalFieldElement):
other_intv = other
else:
# Let type errors from _coerce_ propagate...
other_intv = self._parent(other)
mpfi_union(x.__re, self.__re, other_intv.__re)
mpfi_union(x.__im, self.__im, other_intv.__im)
return x
def center(self):
"""
Returns the closest floating-point approximation to the center
of the interval.
EXAMPLES::
sage: CIF(RIF(1, 2), RIF(3, 4)).center()
1.50000000000000 + 3.50000000000000*I
"""
cdef complex_number.ComplexNumber center
center = complex_number.ComplexNumber(self._parent._middle_field(), None)
mpfi_mid(center.__re, self.__re)
mpfi_mid(center.__im, self.__im)
return center
def __contains__(self, other):
"""
Test whether ``other`` is totally contained in ``self``.
EXAMPLES::
sage: CIF(1, 1) in CIF(RIF(1, 2), RIF(1, 2))
True
"""
# This could be more efficient (and support more types for "other").
return (other.real() in self.real()) and (other.imag() in self.imag())
def contains_zero(self):
"""
Returns ``True`` if ``self`` is an interval containing zero.
EXAMPLES::
sage: CIF(0).contains_zero()
True
sage: CIF(RIF(-1, 1), 1).contains_zero()
False
"""
return mpfi_has_zero(self.__re) and mpfi_has_zero(self.__im)
cpdef ModuleElement _add_(self, ModuleElement right):
"""
Add ``self`` and ``right``.
EXAMPLES::
sage: CIF(2,-3)._add_(CIF(1,-2))
3 - 5*I
"""
cdef ComplexIntervalFieldElement x
x = self._new()
mpfi_add(x.__re, self.__re, (<ComplexIntervalFieldElement>right).__re)
mpfi_add(x.__im, self.__im, (<ComplexIntervalFieldElement>right).__im)
return x
cpdef ModuleElement _sub_(self, ModuleElement right):
"""
Subtract ``self`` by ``right``.
EXAMPLES::
sage: CIF(2,-3)._sub_(CIF(1,-2))
1 - 1*I
"""
cdef ComplexIntervalFieldElement x
x = self._new()
mpfi_sub(x.__re, self.__re, (<ComplexIntervalFieldElement>right).__re)
mpfi_sub(x.__im, self.__im, (<ComplexIntervalFieldElement>right).__im)
return x
cpdef RingElement _mul_(self, RingElement right):
"""
Multiply ``self`` and ``right``.
EXAMPLES::
sage: CIF(2,-3)._mul_(CIF(1,-2))
-4 - 7*I
"""
cdef ComplexIntervalFieldElement x
x = self._new()
cdef mpfi_t t0, t1
mpfi_init2(t0, self._prec)
mpfi_init2(t1, self._prec)
mpfi_mul(t0, self.__re, (<ComplexIntervalFieldElement>right).__re)
mpfi_mul(t1, self.__im, (<ComplexIntervalFieldElement>right).__im)
mpfi_sub(x.__re, t0, t1)
mpfi_mul(t0, self.__re, (<ComplexIntervalFieldElement>right).__im)
mpfi_mul(t1, self.__im, (<ComplexIntervalFieldElement>right).__re)
mpfi_add(x.__im, t0, t1)
mpfi_clear(t0)
mpfi_clear(t1)
return x
def norm(self):
"""
Returns the norm of this complex number.
If `c = a + bi` is a complex number, then the norm of `c` is defined as
the product of `c` and its complex conjugate:
.. MATH::
\text{norm}(c)
=
\text{norm}(a + bi)
=
c \cdot \overline{c}
=
a^2 + b^2.
The norm of a complex number is different from its absolute value.
The absolute value of a complex number is defined to be the square
root of its norm. A typical use of the complex norm is in the
integral domain `\ZZ[i]` of Gaussian integers, where the norm of
each Gaussian integer `c = a + bi` is defined as its complex norm.
.. SEEALSO::
- :meth:`sage.rings.complex_double.ComplexDoubleElement.norm`
EXAMPLES::
sage: CIF(2, 1).norm()
5
sage: CIF(1, -2).norm()
5
"""
return self.norm_c()
cdef real_mpfi.RealIntervalFieldElement norm_c(ComplexIntervalFieldElement self):
cdef real_mpfi.RealIntervalFieldElement x
x = real_mpfi.RealIntervalFieldElement(self._parent._real_field(), None)
cdef mpfi_t t0, t1
mpfi_init2(t0, self._prec)
mpfi_init2(t1, self._prec)
mpfi_sqr(t0, self.__re)
mpfi_sqr(t1, self.__im)
mpfi_add(x.value, t0, t1)
mpfi_clear(t0)
mpfi_clear(t1)
return x
cdef real_mpfi.RealIntervalFieldElement abs_c(ComplexIntervalFieldElement self):
cdef real_mpfi.RealIntervalFieldElement x
x = real_mpfi.RealIntervalFieldElement(self._parent._real_field(), None)
cdef mpfi_t t0, t1
mpfi_init2(t0, self._prec)
mpfi_init2(t1, self._prec)
mpfi_sqr(t0, self.__re)
mpfi_sqr(t1, self.__im)
mpfi_add(x.value, t0, t1)
mpfi_sqrt(x.value, x.value)
mpfi_clear(t0)
mpfi_clear(t1)
return x
cpdef RingElement _div_(self, RingElement right):
"""
Divide ``self`` by ``right``.
EXAMPLES::
sage: CIF(2,-3)._div_(CIF(1,-2))
1.600000000000000? + 0.200000000000000?*I
"""
cdef ComplexIntervalFieldElement x
x = self._new()
cdef mpfi_t a, b, t0, t1, right_nm
mpfi_init2(t0, self._prec)
mpfi_init2(t1, self._prec)
mpfi_init2(a, self._prec)
mpfi_init2(b, self._prec)
mpfi_init2(right_nm, self._prec)
mpfi_sqr(t0, (<ComplexIntervalFieldElement>right).__re)
mpfi_sqr(t1, (<ComplexIntervalFieldElement>right).__im)
mpfi_add(right_nm, t0, t1)
mpfi_div(a, (<ComplexIntervalFieldElement>right).__re, right_nm)
mpfi_div(b, (<ComplexIntervalFieldElement>right).__im, right_nm)
## Do this: x.__re = a * self.__re + b * self.__im
mpfi_mul(t0, a, self.__re)
mpfi_mul(t1, b, self.__im)
mpfi_add(x.__re, t0, t1)
## Do this: x.__im = a * self.__im - b * self.__re
mpfi_mul(t0, a, self.__im)
mpfi_mul(t1, b, self.__re)
mpfi_sub(x.__im, t0, t1)
mpfi_clear(t0)
mpfi_clear(t1)
mpfi_clear(a)
mpfi_clear(b)
mpfi_clear(right_nm)
return x
def __rdiv__(self, left):
"""
Divide ``left`` by ``self``.
EXAMPLES::
sage: CIF(2,-3).__rdiv__(CIF(1,-2))
0.6153846153846154? - 0.0769230769230769?*I
"""
return ComplexIntervalFieldElement(self._parent, left)/self
def __pow__(self, right, modulus):
r"""
Compute `x^y`.
If `y` is an integer, uses multiplication;
otherwise, uses the standard definition `\exp(\log(x) \cdot y)`.
.. WARNING::
If the interval `x` crosses the negative real axis, then we use a
non-standard definition of `\log()` (see the docstring for
:meth:`argument()` for more details). This means that we will not
select the principal value of the power, for part of the input
interval (and that we violate the interval guarantees).
EXAMPLES::
sage: C.<i> = ComplexIntervalField(20)
sage: a = i^2; a
-1
sage: a.parent()
Complex Interval Field with 20 bits of precision
sage: a = (1+i)^7; a
8 - 8*I
sage: (1+i)^(1+i)
0.27396? + 0.58370?*I
sage: a.parent()
Complex Interval Field with 20 bits of precision
sage: (2+i)^(-39)
1.688?e-14 + 1.628?e-14*I
If the interval crosses the negative real axis, then we don't use the
standard branch cut (and we violate the interval guarantees)::
sage: (CIF(-7, RIF(-1, 1)) ^ CIF(0.3)).str(style='brackets')
'[0.99109735947126309 .. 1.1179269966896264] + [1.4042388462787560 .. 1.4984624123369835]*I'
sage: CIF(-7, -1) ^ CIF(0.3)
1.117926996689626? - 1.408500714575360?*I
"""
if isinstance(right, (int, long, integer.Integer)):
return RingElement.__pow__(self, right)
return (self.log() * self.parent()(right)).exp()
def _magma_init_(self, magma):
r"""
Return a string representation of ``self`` in the Magma language.
EXAMPLES::
sage: t = CIF((1, 1.1), 2.5); t
1.1? + 2.5000000000000000?*I
sage: magma(t) # optional - magma # indirect doctest
1.05000000000000 + 2.50000000000000*$.1
sage: t = ComplexIntervalField(100)((1, 4/3), 2.5); t
2.? + 2.5000000000000000000000000000000?*I
sage: magma(t) # optional - magma
1.16666666666666666666666666670 + 2.50000000000000000000000000000*$.1
"""
return "%s![%s, %s]" % (self.parent()._magma_init_(magma), self.center().real(), self.center().imag())
def _interface_init_(self, I=None):
"""
Raise a ``TypeError``.
This function would return the string representation of ``self``
that makes sense as a default representation of a complex
interval in other computer algebra systems. But, most other
computer algebra systems do not support interval arithmetic,
so instead we just raise a ``TypeError``.
Define the appropriate ``_cas_init_`` function if there is a
computer algebra system you would like to support.
EXAMPLES::
sage: n = CIF(1.3939494594)
sage: n._interface_init_()
Traceback (most recent call last):
...
TypeError
Here a conversion to Maxima happens, which results in a ``TypeError``::
sage: a = CIF(2.3)
sage: maxima(a)
Traceback (most recent call last):
...
TypeError
"""
raise TypeError
def _sage_input_(self, sib, coerce):
r"""
Produce an expression which will reproduce this value when evaluated.
EXAMPLES::
sage: sage_input(CIF(RIF(e, pi), RIF(sqrt(2), sqrt(3))), verify=True)
# Verified
CIF(RIF(RR(2.7182818284590451), RR(3.1415926535897936)), RIF(RR(1.4142135623730949), RR(1.7320508075688774)))
sage: sage_input(ComplexIntervalField(64)(2)^I, preparse=False, verify=True)
# Verified
RIF64 = RealIntervalField(64)
RR64 = RealField(64)
ComplexIntervalField(64)(RIF64(RR64('0.769238901363972126565'), RR64('0.769238901363972126619')), RIF64(RR64('0.638961276313634801076'), RR64('0.638961276313634801184')))
sage: from sage.misc.sage_input import SageInputBuilder
sage: sib = SageInputBuilder()
sage: ComplexIntervalField(15)(3+I).log()._sage_input_(sib, False)
{call: {call: {atomic:ComplexIntervalField}({atomic:15})}({call: {call: {atomic:RealIntervalField}({atomic:15})}({call: {call: {atomic:RealField}({atomic:15})}({atomic:1.15125})}, {call: {call: {atomic:RealField}({atomic:15})}({atomic:1.15137})})}, {call: {call: {atomic:RealIntervalField}({atomic:15})}({call: {call: {atomic:RealField}({atomic:15})}({atomic:0.321655})}, {call: {call: {atomic:RealField}({atomic:15})}({atomic:0.321777})})})}
"""
# Interval printing could often be much prettier,
# but I'm feeling lazy :)
return sib(self.parent())(sib(self.real()), sib(self.imag()))
def prec(self):
"""
Return precision of this complex number.
EXAMPLES::
sage: i = ComplexIntervalField(2000).0
sage: i.prec()
2000
"""
return self._parent.prec()
def real(self):
"""
Return real part of ``self``.
EXAMPLES::
sage: i = ComplexIntervalField(100).0
sage: z = 2 + 3*i
sage: x = z.real(); x
2
sage: x.parent()
Real Interval Field with 100 bits of precision
"""
cdef real_mpfi.RealIntervalFieldElement x
x = real_mpfi.RealIntervalFieldElement(self._parent._real_field(), None)
mpfi_set(x.value, self.__re)
return x
def imag(self):
"""
Return imaginary part of ``self``.
EXAMPLES::
sage: i = ComplexIntervalField(100).0
sage: z = 2 + 3*i
sage: x = z.imag(); x
3
sage: x.parent()
Real Interval Field with 100 bits of precision
"""
cdef real_mpfi.RealIntervalFieldElement x
x = real_mpfi.RealIntervalFieldElement(self._parent._real_field(), None)
mpfi_set(x.value, self.__im)
return x
def __neg__(self):
"""
Return the negation of ``self``.
EXAMPLES::
sage: CIF(1.5, 2.5).__neg__()
-1.5000000000000000? - 2.5000000000000000?*I
"""
cdef ComplexIntervalFieldElement x
x = self._new()
mpfi_neg(x.__re, self.__re)
mpfi_neg(x.__im, self.__im)
return x
def __pos__(self):
"""
Return the "positive" of ``self``, which is just ``self``.
EXAMPLES::
sage: CIF(1.5, 2.5).__pos__()
1.5000000000000000? + 2.5000000000000000?*I
"""
return self
def __abs__(self):
"""
Return the absolute value of ``self``.
EXAMPLES::
sage: CIF(1.5, 2.5).__abs__()
2.915475947422650?
"""
return self.abs_c()
def __invert__(self):
"""
Return the multiplicative inverse of ``self``.
EXAMPLES::
sage: I = CIF.0
sage: a = ~(5+I) # indirect doctest
sage: a * (5+I)
1.000000000000000? + 0.?e-16*I
"""
cdef ComplexIntervalFieldElement x
x = self._new()
cdef mpfi_t t0, t1
mpfi_init2(t0, self._prec)
mpfi_init2(t1, self._prec)
mpfi_sqr(t0, self.__re)
mpfi_sqr(t1, self.__im)
mpfi_add(t0, t0, t1) # now t0 is the norm