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_arb.pyx
3599 lines (2909 loc) · 115 KB
/
complex_arb.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
# -*- coding: utf-8
r"""
Arbitrary precision complex balls using Arb
This is a binding to the `Arb library <http://fredrikj.net/arb/>`_; it
may be useful to refer to its documentation for more details.
Parts of the documentation for this module are copied or adapted from
Arb's own documentation, licenced under the GNU General Public License
version 2, or later.
.. SEEALSO::
- :mod:`Real balls using Arb <sage.rings.real_arb>`
- :mod:`Complex interval field (using MPFI) <sage.rings.complex_interval_field>`
- :mod:`Complex intervals (using MPFI) <sage.rings.complex_interval>`
Data Structure
==============
A :class:`ComplexBall` represents a complex number with error bounds. It wraps
an Arb object of type ``acb_t``, which consists of a pair of real number balls
representing the real and imaginary part with separate error bounds. (See the
documentation of :mod:`sage.rings.real_arb` for more information.)
A :class:`ComplexBall` thus represents a rectangle `[m_1-r_1, m_1+r_1] +
[m_2-r_2, m_2+r_2] i` in the complex plane. This is used in Arb instead of a
disk or square representation (consisting of a complex floating-point midpoint
with a single radius), since it allows implementing many operations more
conveniently by splitting into ball operations on the real and imaginary parts.
It also allows tracking when complex numbers have an exact (for example exactly
zero) real part and an inexact imaginary part, or vice versa.
The parents of complex balls are instances of :class:`ComplexBallField`.
The name ``CBF`` is bound to the complex ball field with the default precision
of 53 bits::
sage: CBF is ComplexBallField() is ComplexBallField(53)
True
Comparison
==========
.. WARNING::
In accordance with the semantics of Arb, identical :class:`ComplexBall`
objects are understood to give permission for algebraic simplification.
This assumption is made to improve performance. For example, setting ``z =
x*x`` sets `z` to a ball enclosing the set `\{t^2 : t \in x\}` and not the
(generally larger) set `\{tu : t \in x, u \in x\}`.
Two elements are equal if and only if they are the same object
or if both are exact and equal::
sage: a = CBF(1, 2)
sage: b = CBF(1, 2)
sage: a is b
False
sage: a == b
True
sage: a = CBF(1/3, 1/5)
sage: b = CBF(1/3, 1/5)
sage: a.is_exact()
False
sage: b.is_exact()
False
sage: a is b
False
sage: a == b
False
A ball is non-zero in the sense of usual comparison if and only if it does not
contain zero::
sage: a = CBF(RIF(-0.5, 0.5))
sage: a != 0
False
sage: b = CBF(1/3, 1/5)
sage: b != 0
True
However, ``bool(b)`` returns ``False`` for a ball ``b`` only if ``b`` is exactly
zero::
sage: bool(a)
True
sage: bool(b)
True
sage: bool(CBF.zero())
False
Coercion
========
Automatic coercions work as expected::
sage: bpol = 1/3*CBF(i) + AA(sqrt(2)) + (polygen(RealBallField(20), 'x') + QQbar(i))
sage: bpol
x + [1.41421 +/- 5.09e-6] + [1.33333 +/- 3.97e-6]*I
sage: bpol.parent()
Univariate Polynomial Ring in x over Complex ball field with 20 bits precision
sage: bpol/3
([0.333333 +/- 4.93e-7])*x + [0.47140 +/- 5.39e-6] + [0.44444 +/- 4.98e-6]*I
TESTS::
sage: polygen(CBF, 'x')^3
x^3
::
sage: SR.coerce(CBF(0.42 + 3.33*I))
[0.4200000000000000 +/- 1.56e-17] + [3.330000000000000 +/- 7.11e-17]*I
Check that :trac:`19839` is fixed::
sage: log(SR(CBF(0.42))).pyobject().parent()
Complex ball field with 53 bits precision
Classes and Methods
===================
"""
#*****************************************************************************
# Copyright (C) 2014 Clemens Heuberger <clemens.heuberger@aau.at>
#
# 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.
# http://www.gnu.org/licenses/
#*****************************************************************************
from __future__ import absolute_import
import operator
from cysignals.signals cimport sig_on, sig_str, sig_off, sig_error
import sage.categories.fields
cimport sage.rings.integer
cimport sage.rings.rational
import sage.rings.number_field.number_field as number_field
from cpython.float cimport PyFloat_AS_DOUBLE
from cpython.int cimport PyInt_AS_LONG
from cpython.object cimport Py_LT, Py_LE, Py_EQ, Py_NE, Py_GT, Py_GE
from sage.libs.mpfr cimport MPFR_RNDU
from sage.libs.arb.arb cimport *
from sage.libs.arb.acb cimport *
from sage.libs.arb.acb_hypgeom cimport *
from sage.libs.arb.acb_modular cimport *
from sage.libs.arb.arf cimport arf_init, arf_get_mpfr, arf_set_mpfr, arf_clear, arf_set_mag, arf_set, arf_is_nan
from sage.libs.arb.mag cimport mag_init, mag_clear, mag_add, mag_set_d, MAG_BITS, mag_is_inf, mag_is_finite, mag_zero
from sage.libs.flint.fmpz cimport fmpz_t, fmpz_init, fmpz_get_mpz, fmpz_set_mpz, fmpz_clear, fmpz_abs
from sage.libs.flint.fmpq cimport fmpq_t, fmpq_init, fmpq_set_mpq, fmpq_clear
from sage.libs.gmp.mpz cimport mpz_fits_ulong_p, mpz_fits_slong_p, mpz_get_ui, mpz_get_si, mpz_sgn
from sage.rings.complex_field import ComplexField
from sage.rings.complex_interval_field import ComplexIntervalField
from sage.rings.integer_ring import ZZ
from sage.rings.number_field.number_field_element_quadratic cimport NumberFieldElement_quadratic
from sage.rings.real_arb cimport mpfi_to_arb, arb_to_mpfi, real_part_of_quadratic_element_to_arb
from sage.rings.real_arb import RealBallField
from sage.rings.real_mpfr cimport RealField_class, RealField, RealNumber
from sage.rings.ring import Field
from sage.structure.element cimport Element, ModuleElement
from sage.structure.parent cimport Parent
from sage.structure.unique_representation import UniqueRepresentation
cdef void ComplexIntervalFieldElement_to_acb(
acb_t target,
ComplexIntervalFieldElement source):
"""
Convert a :class:`ComplexIntervalFieldElement` to an ``acb``.
INPUT:
- ``target`` -- an ``acb_t``
- ``source`` -- a :class:`ComplexIntervalFieldElement`
OUTPUT:
None.
"""
cdef long precision
precision = source.parent().precision()
mpfi_to_arb(acb_realref(target), source.__re, precision)
mpfi_to_arb(acb_imagref(target), source.__im, precision)
cdef int acb_to_ComplexIntervalFieldElement(
ComplexIntervalFieldElement target,
const acb_t source) except -1:
"""
Convert an ``acb`` to a :class:`ComplexIntervalFieldElement`.
INPUT:
- ``target`` -- a :class:`ComplexIntervalFieldElement`
- ``source`` -- an ``acb_t``
OUTPUT:
A :class:`ComplexIntervalFieldElement`.
"""
cdef long precision = target._prec
arb_to_mpfi(target.__re, acb_realref(source), precision)
arb_to_mpfi(target.__im, acb_imagref(source), precision)
return 0
class ComplexBallField(UniqueRepresentation, Field):
r"""
An approximation of the field of complex numbers using pairs of mid-rad
intervals.
INPUT:
- ``precision`` -- an integer `\ge 2`.
EXAMPLES::
sage: CBF(1)
1.000000000000000
TESTS::
sage: ComplexBallField(0)
Traceback (most recent call last):
...
ValueError: Precision must be at least 2.
sage: ComplexBallField(1)
Traceback (most recent call last):
...
ValueError: Precision must be at least 2.
"""
Element = ComplexBall
@staticmethod
def __classcall__(cls, long precision=53, category=None):
r"""
Normalize the arguments for caching.
TESTS::
sage: ComplexBallField(53) is ComplexBallField()
True
"""
return super(ComplexBallField, cls).__classcall__(cls, precision, category)
def __init__(self, precision, category):
r"""
Initialize the complex ball field.
INPUT:
- ``precision`` -- an integer `\ge 2`.
EXAMPLES::
sage: CBF(1)
1.000000000000000
TESTS::
sage: CBF.base()
Real ball field with 53 bits precision
sage: CBF.base_ring()
Real ball field with 53 bits precision
There are direct coercions from ZZ and QQ (for which arb provides
construction functions)::
sage: CBF.coerce_map_from(ZZ)
Coercion map:
From: Integer Ring
To: Complex ball field with 53 bits precision
sage: CBF.coerce_map_from(QQ)
Coercion map:
From: Rational Field
To: Complex ball field with 53 bits precision
Various other coercions are available through real ball fields or CLF::
sage: CBF.coerce_map_from(RLF)
Composite map:
From: Real Lazy Field
To: Complex ball field with 53 bits precision
Defn: Coercion map:
From: Real Lazy Field
To: Real ball field with 53 bits precision
then
Coercion map:
From: Real ball field with 53 bits precision
To: Complex ball field with 53 bits precision
sage: CBF.has_coerce_map_from(AA)
True
sage: CBF.has_coerce_map_from(QuadraticField(-1))
True
sage: CBF.has_coerce_map_from(QQbar)
True
sage: CBF.has_coerce_map_from(CLF)
True
"""
if precision < 2:
raise ValueError("Precision must be at least 2.")
real_field = RealBallField(precision)
super(ComplexBallField, self).__init__(
base_ring=real_field,
category=category or sage.categories.fields.Fields().Infinite())
self._prec = precision
from sage.rings.rational_field import QQ
from sage.rings.real_lazy import CLF
self._populate_coercion_lists_([ZZ, QQ, real_field, CLF])
def _real_field(self):
"""
TESTS::
sage: CBF._real_field() is RBF
True
"""
return self._base
def _repr_(self):
r"""
String representation of ``self``.
EXAMPLES::
sage: ComplexBallField()
Complex ball field with 53 bits precision
sage: ComplexBallField(106)
Complex ball field with 106 bits precision
"""
return "Complex ball field with {} bits precision".format(self._prec)
def construction(self):
"""
Return the construction of a complex ball field as the algebraic
closure of the real ball field with the same precision.
EXAMPLES::
sage: functor, base = CBF.construction()
sage: functor, base
(AlgebraicClosureFunctor, Real ball field with 53 bits precision)
sage: functor(base) is CBF
True
"""
from sage.categories.pushout import AlgebraicClosureFunctor
return (AlgebraicClosureFunctor(), self._base)
def complex_field(self):
"""
Return the complex ball field with the same precision, i.e. ``self``
EXAMPLES::
sage: CBF.complex_field() is CBF
True
"""
return ComplexBallField(self._prec)
def ngens(self):
r"""
Return 1 as the only generator is the imaginary unit.
EXAMPLES::
sage: CBF.ngens()
1
"""
return 1
def gen(self, i):
r"""
For i = 0, return the imaginary unit in this complex ball field.
EXAMPLES::
sage: CBF.0
1.000000000000000*I
sage: CBF.gen(1)
Traceback (most recent call last):
...
ValueError: only one generator
"""
if i == 0:
return self(0, 1)
else:
raise ValueError("only one generator")
def gens(self):
r"""
Return the tuple of generators of this complex ball field, i.e.
``(i,)``.
EXAMPLES::
sage: CBF.gens()
(1.000000000000000*I,)
sage: CBF.gens_dict()
{'1.000000000000000*I': 1.000000000000000*I}
"""
return (self(0, 1),)
def _coerce_map_from_(self, other):
r"""
Parents that canonically coerce into complex ball fields include:
- anything that coerces into the corresponding real ball field;
- real and complex ball fields with a larger precision;
- various exact or lazy parents representing subsets of the complex
numbers, such as ``QQbar``, ``CLF``, and number fields equipped
with complex embeddings.
TESTS::
sage: CBF.coerce_map_from(CBF)
Identity endomorphism of Complex ball field with 53 bits precision
sage: CBF.coerce_map_from(ComplexBallField(100))
Coercion map:
From: Complex ball field with 100 bits precision
To: Complex ball field with 53 bits precision
sage: CBF.has_coerce_map_from(ComplexBallField(42))
False
sage: CBF.has_coerce_map_from(RealBallField(54))
True
sage: CBF.has_coerce_map_from(RealBallField(52))
False
sage: CBF.has_coerce_map_from(QuadraticField(-2))
True
sage: CBF.has_coerce_map_from(QuadraticField(2, embedding=None))
False
Check that there are no coercions from interval or floating-point parents::
sage: CBF.has_coerce_map_from(RIF)
False
sage: CBF.has_coerce_map_from(CIF)
False
sage: CBF.has_coerce_map_from(RR)
False
sage: CBF.has_coerce_map_from(CC)
False
"""
if isinstance(other, (RealBallField, ComplexBallField)):
return (other._prec >= self._prec)
elif isinstance(other, number_field.NumberField_quadratic):
emb = other.coerce_embedding()
if emb is not None:
return self.has_coerce_map_from(emb.codomain())
def _element_constructor_(self, x=None, y=None):
r"""
Convert (x, y) to an element of this complex ball field, perhaps
non-canonically.
INPUT:
- ``x``, ``y`` (optional) -- either a complex number, interval or ball,
or two real ones (see examples below for more information on accepted
number types).
EXAMPLES::
sage: CBF()
0
sage: CBF(1) # indirect doctest
1.000000000000000
sage: CBF(1, 1)
1.000000000000000 + 1.000000000000000*I
sage: CBF(pi, sqrt(2))
[3.141592653589793 +/- 5.61e-16] + [1.414213562373095 +/- 4.10e-16]*I
sage: CBF(I)
1.000000000000000*I
sage: CBF(pi+I/3)
[3.141592653589793 +/- 5.61e-16] + [0.3333333333333333 +/- 7.04e-17]*I
sage: CBF(QQbar(i/7))
[0.1428571428571428 +/- 9.09e-17]*I
sage: CBF(AA(sqrt(2)))
[1.414213562373095 +/- 4.10e-16]
sage: CBF(CIF(0, 1))
1.000000000000000*I
sage: CBF(RBF(1/3))
[0.3333333333333333 +/- 7.04e-17]
sage: CBF(RBF(1/3), RBF(1/6))
[0.3333333333333333 +/- 7.04e-17] + [0.1666666666666667 +/- 7.04e-17]*I
sage: CBF(1/3)
[0.3333333333333333 +/- 7.04e-17]
sage: CBF(1/3, 1/6)
[0.3333333333333333 +/- 7.04e-17] + [0.1666666666666667 +/- 7.04e-17]*I
sage: ComplexBallField(106)(1/3, 1/6)
[0.33333333333333333333333333333333 +/- 6.94e-33] + [0.16666666666666666666666666666666 +/- 7.70e-33]*I
sage: NF.<a> = QuadraticField(-2)
sage: CBF(1/5 + a/2)
[0.2000000000000000 +/- 4.45e-17] + [0.707106781186547 +/- 5.86e-16]*I
sage: CBF(infinity, NaN)
[+/- inf] + nan*I
sage: CBF(x)
Traceback (most recent call last):
...
TypeError: unable to convert x to a ComplexBall
.. SEEALSO::
:meth:`sage.rings.real_arb.RealBallField._element_constructor_`
TESTS::
sage: CBF(1+I, 2)
Traceback (most recent call last):
...
ValueError: nonzero imaginary part
"""
try:
return self.element_class(self, x, y)
except TypeError:
pass
if y is None:
try:
x = self._base(x)
return self.element_class(self, x)
except (TypeError, ValueError):
pass
try:
y = self._base(x.imag())
x = self._base(x.real())
return self.element_class(self, x, y)
except (AttributeError, TypeError):
pass
try:
x = ComplexIntervalField(self._prec)(x)
return self.element_class(self, x)
except TypeError:
pass
raise TypeError("unable to convert {!r} to a ComplexBall".format(x))
else:
x = self._base(x)
y = self._base(y)
return self.element_class(self, x, y)
def _an_element_(self):
r"""
Construct an element.
EXAMPLES::
sage: CBF.an_element() # indirect doctest
[0.3333333333333333 +/- 1.49e-17] - [0.1666666666666667 +/- 4.26e-17]*I
"""
return self(1.0/3, -1.0/6)
def precision(self):
"""
Return the bit precision used for operations on elements of this field.
EXAMPLES::
sage: ComplexBallField().precision()
53
"""
return self._prec
def is_exact(self):
"""
Complex ball fields are not exact.
EXAMPLES::
sage: ComplexBallField().is_exact()
False
"""
return False
def is_finite(self):
"""
Complex ball fields are infinite.
They already specify it via their category, but we currently need to
re-implement this method due to the legacy implementation in
:class:`sage.rings.ring.Ring`.
EXAMPLES::
sage: ComplexBallField().is_finite()
False
"""
return False
def characteristic(self):
"""
Complex ball fields have characteristic zero.
EXAMPLES::
sage: ComplexBallField().characteristic()
0
"""
return 0
def some_elements(self):
"""
Complex ball fields contain elements with exact, inexact, infinite, or
undefined real and imaginary parts.
EXAMPLES::
sage: CBF.some_elements()
[1.000000000000000,
-0.5000000000000000*I,
1.000000000000000 + [0.3333333333333333 +/- 1.49e-17]*I,
[-0.3333333333333333 +/- 1.49e-17] + 0.2500000000000000*I,
[-2.175556475109056e+181961467118333366510562 +/- 1.29e+181961467118333366510545],
[+/- inf],
[0.3333333333333333 +/- 1.49e-17] + [+/- inf]*I,
[+/- inf] + [+/- inf]*I,
nan,
nan + nan*I,
[+/- inf] + nan*I]
"""
return [self(1), self(0, -1./2), self(1, 1./3), self(-1./3, 1./4),
-self(1, 1)**(sage.rings.integer.Integer(2)**80),
self('inf'), self(1./3, 'inf'), self('inf', 'inf'),
self('nan'), self('nan', 'nan'), self('inf', 'nan')]
cdef inline bint _do_sig(long prec):
"""
Whether signal handlers should be installed for calls to arb.
"""
return (prec > 1000)
cdef inline long prec(ComplexBall ball):
return ball._parent._prec
cdef inline Parent real_ball_field(ComplexBall ball):
return ball._parent._base
cdef class ComplexBall(RingElement):
"""
Hold one ``acb_t`` of the `Arb library
<http://fredrikj.net/arb/>`_
EXAMPLES::
sage: a = ComplexBallField()(1, 1)
sage: a
1.000000000000000 + 1.000000000000000*I
"""
def __cinit__(self):
"""
Allocate memory for the encapsulated value.
EXAMPLES::
sage: ComplexBallField(2)(0) # indirect doctest
0
"""
acb_init(self.value)
def __dealloc__(self):
"""
Deallocate memory of the encapsulated value.
EXAMPLES::
sage: a = ComplexBallField(2)(0) # indirect doctest
sage: del a
"""
acb_clear(self.value)
def __init__(self, parent, x=None, y=None):
"""
Initialize the :class:`ComplexBall`.
INPUT:
- ``parent`` -- a :class:`ComplexBallField`.
- ``x``, ``y`` (optional) -- either a complex number, interval or ball,
or two real ones.
.. SEEALSO:: :meth:`ComplexBallField._element_constructor_`
TESTS::
sage: from sage.rings.complex_arb import ComplexBall
sage: CBF53, CBF100 = ComplexBallField(53), ComplexBallField(100)
sage: ComplexBall(CBF100)
0
sage: ComplexBall(CBF100, ComplexBall(CBF53, ComplexBall(CBF100, 1/3)))
[0.333333333333333333333333333333 +/- 4.65e-31]
sage: ComplexBall(CBF100, RBF(pi))
[3.141592653589793 +/- 5.61e-16]
sage: ComplexBall(CBF100, -3r)
-3.000000000000000000000000000000
sage: ComplexBall(CBF100, 10^100)
1.000000000000000000000000000000e+100
sage: ComplexBall(CBF100, CIF(1, 2))
1.000000000000000000000000000000 + 2.000000000000000000000000000000*I
sage: ComplexBall(CBF100, RBF(1/3), RBF(1))
[0.3333333333333333 +/- 7.04e-17] + 1.000000000000000000000000000000*I
sage: ComplexBall(CBF100, 1, 2)
Traceback (most recent call last):
...
TypeError: unsupported initializer
sage: NF.<a> = QuadraticField(-1, embedding=CC(0, -1))
sage: CBF(a)
-1.000000000000000*I
sage: NF.<a> = QuadraticField(-1, embedding=None)
sage: CBF(a)
Traceback (most recent call last):
...
ValueError: need an embedding
"""
cdef fmpz_t tmpz
cdef fmpq_t tmpq
cdef NumberFieldElement_quadratic x_as_qe
cdef long myprec
RingElement.__init__(self, parent)
if x is None:
return
elif y is None:
if isinstance(x, ComplexBall):
acb_set(self.value, (<ComplexBall> x).value)
elif isinstance(x, RealBall):
acb_set_arb(self.value, (<RealBall> x).value)
elif isinstance(x, int):
acb_set_si(self.value, PyInt_AS_LONG(x))
elif isinstance(x, sage.rings.integer.Integer):
if _do_sig(prec(self)): sig_on()
fmpz_init(tmpz)
fmpz_set_mpz(tmpz, (<sage.rings.integer.Integer> x).value)
acb_set_fmpz(self.value, tmpz)
fmpz_clear(tmpz)
if _do_sig(prec(self)): sig_off()
elif isinstance(x, sage.rings.rational.Rational):
if _do_sig(prec(self)): sig_on()
fmpq_init(tmpq)
fmpq_set_mpq(tmpq, (<sage.rings.rational.Rational> x).value)
acb_set_fmpq(self.value, tmpq, prec(self))
fmpq_clear(tmpq)
if _do_sig(prec(self)): sig_off()
elif isinstance(x, ComplexIntervalFieldElement):
ComplexIntervalFieldElement_to_acb(self.value,
<ComplexIntervalFieldElement> x)
elif isinstance(x, NumberFieldElement_quadratic):
x_as_qe = <NumberFieldElement_quadratic> x
real_part_of_quadratic_element_to_arb(acb_realref(self.value),
x_as_qe, prec(self))
myprec = prec(self) + 4
if mpz_sgn(x_as_qe.D.value) < 0:
if x_as_qe._parent._embedding is None:
raise ValueError("need an embedding")
fmpz_init(tmpz)
fmpz_set_mpz(tmpz, x_as_qe.D.value)
fmpz_abs(tmpz, tmpz)
arb_sqrt_fmpz(acb_imagref(self.value), tmpz, myprec)
fmpz_set_mpz(tmpz, x_as_qe.b)
arb_mul_fmpz(acb_imagref(self.value), acb_imagref(self.value), tmpz, myprec)
fmpz_set_mpz(tmpz, x_as_qe.denom)
arb_div_fmpz(acb_imagref(self.value), acb_imagref(self.value), tmpz, prec(self))
fmpz_clear(tmpz)
if not x_as_qe.standard_embedding:
acb_conj(self.value, self.value)
else:
raise TypeError("unsupported initializer")
elif isinstance(x, RealBall) and isinstance(y, RealBall):
arb_set(acb_realref(self.value), (<RealBall> x).value)
arb_set(acb_imagref(self.value), (<RealBall> y).value)
else:
raise TypeError("unsupported initializer")
cdef ComplexBall _new(self):
"""
Return a new complex ball element with the same parent as ``self``.
"""
cdef ComplexBall x
x = ComplexBall.__new__(ComplexBall)
x._parent = self._parent
return x
def __hash__(self):
"""
TESTS::
sage: hash(CBF(1/3)) == hash(RBF(1/3))
True
sage: hash(CBF(1/3 + 2*i)) != hash(CBF(1/3 + i))
True
"""
if self.is_real():
return hash(self.real())
else:
return (hash(self.real()) // 3) ^ hash(self.imag())
def _repr_(self):
"""
Return a string representation of ``self``.
OUTPUT:
A string.
EXAMPLES::
sage: CBF(1/3)
[0.3333333333333333 +/- 7.04e-17]
sage: CBF(0, 1/3)
[0.3333333333333333 +/- 7.04e-17]*I
sage: CBF(1/3, 1/6)
[0.3333333333333333 +/- 7.04e-17] + [0.1666666666666667 +/- 7.04e-17]*I
TESTS::
sage: CBF(1-I/2)
1.000000000000000 - 0.5000000000000000*I
"""
cdef arb_t real = acb_realref(self.value)
cdef arb_t imag = acb_imagref(self.value)
if arb_is_zero(imag):
return self.real()._repr_()
elif arb_is_zero(real):
return "{}*I".format(self.imag()._repr_())
elif arb_is_exact(imag) and arb_is_negative(imag):
return "{} - {}*I".format(self.real()._repr_(),
(-self.imag())._repr_())
else:
return "{} + {}*I".format(self.real()._repr_(),
self.imag()._repr_())
def _is_atomic(self):
r"""
Declare that complex balls print atomically in some cases.
TESTS::
sage: CBF(-1/3)._is_atomic()
True
This method should in principle ensure that ``CBF['x']([1, -1/3])``
is printed as::
sage: CBF['x']([1, -1/3]) # todo - not tested
[-0.3333333333333333 +/- 7.04e-17]*x + 1.000000000000000
However, this facility is not really used in Sage at this point, and we
still get::
sage: CBF['x']([1, -1/3])
([-0.3333333333333333 +/- 7.04e-17])*x + 1.000000000000000
"""
return self.is_real() or self.real().is_zero()
# Conversions
cpdef ComplexIntervalFieldElement _complex_mpfi_(self, parent):
"""
Return :class:`ComplexIntervalFieldElement` of the same value.
EXAMPLES::
sage: CIF(CBF(1/3, 1/3)) # indirect doctest
0.3333333333333333? + 0.3333333333333333?*I
"""
cdef ComplexIntervalFieldElement res = parent.zero()
res = res._new() # FIXME after modernizing CIF
acb_to_ComplexIntervalFieldElement(res, self.value)
return res
def _integer_(self, _):
"""
Check that this ball contains a single integer and return that integer.
EXAMPLES::
sage: ZZ(CBF(-42, RBF(.1, rad=.2))) # indirect doctest
-42
sage: ZZ(CBF(i))
Traceback (most recent call last):
...
ValueError: 1.000000000000000*I does not contain a unique integer
"""
cdef sage.rings.integer.Integer res
cdef fmpz_t tmp
fmpz_init(tmp)
try:
if acb_get_unique_fmpz(tmp, self.value):
res = sage.rings.integer.Integer.__new__(sage.rings.integer.Integer)
fmpz_get_mpz(res.value, tmp)
else:
raise ValueError("{} does not contain a unique integer".format(self))
finally:
fmpz_clear(tmp)
return res
def _rational_(self):
"""
Check that this ball contains a single rational number and return that
number.
EXAMPLES::
sage: QQ(CBF(12345/2^5))
12345/32
sage: QQ(CBF(i))
Traceback (most recent call last):
...
ValueError: 1.000000000000000*I does not contain a unique rational number
"""
if acb_is_real(self.value) and acb_is_exact(self.value):
return self.real().mid().exact_rational()
else:
raise ValueError("{} does not contain a unique rational number".format(self))
def _complex_mpfr_field_(self, parent):
r"""
Convert this complex ball to a complex number.
INPUT:
- ``parent`` - :class:`~sage.rings.complex_field.ComplexField_class`,
target parent.
EXAMPLES::
sage: CC(CBF(1/3, 1/3))
0.333333333333333 + 0.333333333333333*I
sage: ComplexField(100)(CBF(1/3, 1/3))
0.33333333333333331482961625625 + 0.33333333333333331482961625625*I
"""
real_field = parent._base
return parent(real_field(self.real()), real_field(self.imag()))
def _real_mpfi_(self, parent):
r"""
Try to convert this complex ball to a real interval.
Fail if the imaginary part is not exactly zero.
INPUT:
- ``parent`` - :class:`~sage.rings.real_mpfi.RealIntervalField_class`,
target parent.
EXAMPLES::
sage: RIF(CBF(RBF(1/3, rad=1e-5)))
0.3334?
sage: RIF(CBF(RBF(1/3, rad=1e-5), 1e-10))
Traceback (most recent call last):
...
ValueError: nonzero imaginary part
"""
if acb_is_real(self.value):
return parent(self.real())
else:
raise ValueError("nonzero imaginary part")
def _mpfr_(self, parent):
r"""
Try to convert this complex ball to a real number.
Fail if the imaginary part is not exactly zero.
INPUT:
- ``parent`` - :class:`~sage.rings.real_mpfr.RealField_class`,
target parent.
EXAMPLES::
sage: RR(CBF(1/3))
0.333333333333333
sage: RR(CBF(1, 1/3) - CBF(0, 1/3))
Traceback (most recent call last):
...
ValueError: nonzero imaginary part
"""
if acb_is_real(self.value):
return parent(self.real())
else:
raise ValueError("nonzero imaginary part")
def __float__(self):
"""
Convert ``self`` to a ``float``.
EXAMPLES::
sage: float(CBF(1))
1.0
sage: float(CBF(1,1))