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
/
real_mpfi.pyx
5145 lines (4265 loc) · 159 KB
/
real_mpfi.pyx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
r"""
Arbitrary Precision Real Intervals
AUTHORS:
- Carl Witty (2007-01-21): based on ``real_mpfr.pyx``; changed it to
use mpfi rather than mpfr.
- William Stein (2007-01-24): modifications and clean up and docs, etc.
- Niles Johnson (2010-08): :trac:`3893`: ``random_element()`` should pass
on ``*args`` and ``**kwds``.
- Travis Scrimshaw (2012-10-20): Fixing scientific notation output
to fix :trac:`13634`.
- Travis Scrimshaw (2012-11-02): Added doctests for full coverage
This is a straightforward binding to the MPFI library; it may be
useful to refer to its documentation for more details.
An interval is represented as a pair of floating-point numbers `a`
and `b` (where `a \leq b`) and is printed as a standard floating-point
number with a question mark (for instance, ``3.1416?``). The question
mark indicates that the preceding digit may have an error of `\pm 1`.
These floating-point numbers are implemented using MPFR (the same
as the :class:`RealNumber` elements of
:class:`~sage.rings.real_mpfr.RealField_class`).
There is also an alternate method of printing, where the interval
prints as ``[a .. b]`` (for instance, ``[3.1415 .. 3.1416]``).
The interval represents the set `\{ x : a \leq x \leq b \}` (so if `a = b`,
then the interval represents that particular floating-point number). The
endpoints can include positive and negative infinity, with the
obvious meaning. It is also possible to have a ``NaN`` (Not-a-Number)
interval, which is represented by having either endpoint be ``NaN``.
PRINTING:
There are two styles for printing intervals: 'brackets' style and
'question' style (the default).
In question style, we print the "known correct" part of the number,
followed by a question mark. The question mark indicates that the
preceding digit is possibly wrong by `\pm 1`.
::
sage: RIF(sqrt(2))
1.414213562373095?
However, if the interval is precise (its lower bound is equal to
its upper bound) and equal to a not-too-large integer, then we just
print that integer.
::
sage: RIF(0)
0
sage: RIF(654321)
654321
::
sage: RIF(123, 125)
124.?
sage: RIF(123, 126)
1.3?e2
As we see in the last example, question style can discard almost a
whole digit's worth of precision. We can reduce this by allowing
"error digits": an error following the question mark, that gives
the maximum error of the digit(s) before the question mark. If the
error is absent (which it always is in the default printing), then
it is taken to be 1.
::
sage: RIF(123, 126).str(error_digits=1)
'125.?2'
sage: RIF(123, 127).str(error_digits=1)
'125.?2'
sage: v = RIF(-e, pi); v
0.?e1
sage: v.str(error_digits=1)
'1.?4'
sage: v.str(error_digits=5)
'0.2117?29300'
Error digits also sometimes let us indicate that the interval is
actually equal to a single floating-point number::
sage: RIF(54321/256)
212.19140625000000?
sage: RIF(54321/256).str(error_digits=1)
'212.19140625000000?0'
In brackets style, intervals are printed with the left value
rounded down and the right rounded up, which is conservative, but
in some ways unsatisfying.
Consider a 3-bit interval containing exactly the floating-point
number 1.25. In round-to-nearest or round-down, this prints as 1.2;
in round-up, this prints as 1.3. The straightforward options, then,
are to print this interval as ``[1.2 .. 1.2]`` (which does not even
contain the true value, 1.25), or to print it as ``[1.2 .. 1.3]``
(which gives the impression that the upper and lower bounds are not
equal, even though they really are). Neither of these is very
satisfying, but we have chosen the latter.
::
sage: R = RealIntervalField(3)
sage: a = R(1.25)
sage: a.str(style='brackets')
'[1.2 .. 1.3]'
sage: a == 1.25
True
sage: a == 2
False
COMPARISONS:
Comparison operations (``==``, ``!=``, ``<``, ``<=``, ``>``, ``>=``)
return ``True`` if every value in the first interval has the given relation
to every value in the second interval. The ``cmp(a, b)`` function works
differently; it compares two intervals lexicographically. (However, the
behavior is not specified if given a non-interval and an interval.)
This convention for comparison operators has good and bad points. The
good:
- Expected transitivity properties hold (if ``a > b`` and ``b == c``, then
``a > c``; etc.)
- if ``a > b``, then ``cmp(a, b) == 1``; if ``a == b``, then ``cmp(a,b) == 0``;
if ``a < b``, then ``cmp(a, b) == -1``
- ``a == 0`` is true if the interval contains only the floating-point number
0; similarly for ``a == 1``
- ``a > 0`` means something useful (that every value in the interval is
greater than 0)
The bad:
- Trichotomy fails to hold: there are values ``(a,b)`` such that none of
``a < b``, ``a == b``, or ``a > b`` are true
- It is not the case that if ``cmp(a, b) == 0`` then ``a == b``, or that if
``cmp(a, b) == 1`` then ``a > b``, or that if ``cmp(a, b) == -1`` then
``a < b``
- There are values ``a`` and ``b`` such that ``a <= b`` but neither ``a < b``
nor ``a == b`` hold.
.. NOTE::
Intervals ``a`` and ``b`` overlap iff ``not(a != b)``.
EXAMPLES::
sage: 0 < RIF(1, 2)
True
sage: 0 == RIF(0)
True
sage: not(0 == RIF(0, 1))
True
sage: not(0 != RIF(0, 1))
True
sage: 0 <= RIF(0, 1)
True
sage: not(0 < RIF(0, 1))
True
sage: cmp(RIF(0), RIF(0, 1))
-1
sage: cmp(RIF(0, 1), RIF(0))
1
sage: cmp(RIF(0, 1), RIF(1))
-1
sage: cmp(RIF(0, 1), RIF(0, 1))
0
Comparison with infinity is defined through coercion to the infinity
ring where semi-infinite intervals are sent to their central value
(plus or minus infinity); This implements the above convention for
inequalities::
sage: InfinityRing.has_coerce_map_from(RIF)
True
sage: -oo < RIF(-1,1) < oo
True
sage: -oo < RIF(0,oo) <= oo
True
sage: -oo <= RIF(-oo,-1) < oo
True
Comparison by equality shows what the semi-infinite intervals actually
coerce to::
sage: RIF(1,oo) == oo
True
sage: RIF(-oo,-1) == -oo
True
For lack of a better value in the infinity ring, the doubly infinite
interval coerces to plus infinity::
sage: RIF(-oo,oo) == oo
True
"""
############################################################################
#
# Sage: System for Algebra and Geometry Experimentation
#
# Copyright (C) 2005-2006 William Stein <wstein@gmail.com>
#
# http://www.gnu.org/licenses/
############################################################################
import math # for log
import sys
include 'sage/ext/interrupt.pxi'
include "sage/ext/stdsage.pxi"
include "sage/ext/cdefs.pxi"
from cpython.mem cimport *
from cpython.string cimport *
from sage.misc.package import is_package_installed
cimport sage.rings.ring
import sage.rings.ring
cimport sage.structure.element
from sage.structure.element cimport RingElement, Element, ModuleElement
import sage.structure.element
cimport real_mpfr
from real_mpfr cimport RealField_class, RealNumber
from real_mpfr import RealField
import real_mpfr
import operator
from integer import Integer
from integer cimport Integer
from real_double import RealDoubleElement
from real_double cimport RealDoubleElement
import sage.rings.complex_field
import sage.rings.infinity
from sage.structure.parent_gens cimport ParentWithGens
cdef class RealIntervalFieldElement(sage.structure.element.RingElement)
#*****************************************************************************
#
# Implementation
#
#*****************************************************************************
# Global settings
printing_style = 'question'
printing_error_digits = 0
cdef double LOG_TEN_TWO_PLUS_EPSILON = 3.321928094887363 # a small overestimate of log(10,2)
#*****************************************************************************
#
# Real Field
#
#*****************************************************************************
# The real field is in Cython, so mpfi elements will have access to
# their parent via direct C calls, which will be faster.
cdef public dict RealIntervalField_cache = {}
cpdef RealIntervalField_class RealIntervalField(prec=53, sci_not=False):
r"""
Construct a :class:`RealIntervalField_class`, with caching.
INPUT:
- ``prec`` -- (integer) precision; default = 53:
The number of bits used to represent the mantissa of a
floating-point number. The precision can be any integer between
:func:`mpfr_prec_min()` and :func:`mpfr_prec_max()`. In the current
implementation, :func:`mpfr_prec_min()` is equal to 2.
- ``sci_not`` -- (default: ``False``) whether or not to display using
scientific notation
EXAMPLES::
sage: RealIntervalField()
Real Interval Field with 53 bits of precision
sage: RealIntervalField(200, sci_not=True)
Real Interval Field with 200 bits of precision
sage: RealIntervalField(53) is RIF
True
sage: RealIntervalField(200) is RIF
False
sage: RealIntervalField(200) is RealIntervalField(200)
True
See the documentation for :class:`RealIntervalField_class
<sage.rings.real_mpfi.RealIntervalField_class>` for many more
examples.
"""
try:
return RealIntervalField_cache[prec, sci_not]
except KeyError:
RealIntervalField_cache[prec, sci_not] = R = RealIntervalField_class(prec, sci_not)
return R
cdef class RealIntervalField_class(sage.rings.ring.Field):
"""
Class of the real interval field.
INPUT:
- ``prec`` -- (integer) precision; default = 53 ``prec`` is
the number of bits used to represent the mantissa of a
floating-point number. The precision can be any integer between
:func:`~sage.rings.real_mpfr.mpfr_prec_min()` and
:func:`~sage.rings.real_mpfr.mpfr_prec_max()`. In the current
implementation, :func:`~sage.rings.real_mpfr.mpfr_prec_min()`
is equal to 2.
- ``sci_not`` -- (default: ``False``) whether or not to display using
scientific notation
EXAMPLES::
sage: RealIntervalField(10)
Real Interval Field with 10 bits of precision
sage: RealIntervalField()
Real Interval Field with 53 bits of precision
sage: RealIntervalField(100000)
Real Interval Field with 100000 bits of precision
.. NOTE::
The default precision is 53, since according to the GMP manual:
'mpfr should be able to exactly reproduce all computations with
double-precision machine floating-point numbers (double type in
C), except the default exponent range is much wider and
subnormal numbers are not implemented.'
EXAMPLES:
Creation of elements.
First with default precision. First we coerce elements of various
types, then we coerce intervals::
sage: RIF = RealIntervalField(); RIF
Real Interval Field with 53 bits of precision
sage: RIF(3)
3
sage: RIF(RIF(3))
3
sage: RIF(pi)
3.141592653589794?
sage: RIF(RealField(53)('1.5'))
1.5000000000000000?
sage: RIF(-2/19)
-0.1052631578947369?
sage: RIF(-3939)
-3939
sage: RIF(-3939r)
-3939
sage: RIF('1.5')
1.5000000000000000?
sage: R200 = RealField(200)
sage: RIF(R200.pi())
3.141592653589794?
The base must be explicitly specified as a named parameter::
sage: RIF('101101', base=2)
45
sage: RIF('+infinity')
[+infinity .. +infinity]
sage: RIF('[1..3]').str(style='brackets')
'[1.0000000000000000 .. 3.0000000000000000]'
Next we coerce some 2-tuples, which define intervals::
sage: RIF((-1.5, -1.3))
-1.4?
sage: RIF((RDF('-1.5'), RDF('-1.3')))
-1.4?
sage: RIF((1/3,2/3)).str(style='brackets')
'[0.33333333333333331 .. 0.66666666666666675]'
The extra parentheses aren't needed::
sage: RIF(1/3,2/3).str(style='brackets')
'[0.33333333333333331 .. 0.66666666666666675]'
sage: RIF((1,2)).str(style='brackets')
'[1.0000000000000000 .. 2.0000000000000000]'
sage: RIF((1r,2r)).str(style='brackets')
'[1.0000000000000000 .. 2.0000000000000000]'
sage: RIF((pi, e)).str(style='brackets')
'[2.7182818284590455 .. 3.1415926535897932]'
Values which can be represented as an exact floating-point number
(of the precision of this ``RealIntervalField``) result in a precise
interval, where the lower bound is equal to the upper bound (even
if they print differently). Other values typically result in an
interval where the lower and upper bounds are adjacent
floating-point numbers.
::
sage: def check(x):
... return (x, x.lower() == x.upper())
sage: check(RIF(pi))
(3.141592653589794?, False)
sage: check(RIF(RR(pi)))
(3.1415926535897932?, True)
sage: check(RIF(1.5))
(1.5000000000000000?, True)
sage: check(RIF('1.5'))
(1.5000000000000000?, True)
sage: check(RIF(0.1))
(0.10000000000000001?, True)
sage: check(RIF(1/10))
(0.10000000000000000?, False)
sage: check(RIF('0.1'))
(0.10000000000000000?, False)
Similarly, when specifying both ends of an interval, the lower end
is rounded down and the upper end is rounded up::
sage: outward = RIF(1/10, 7/10); outward.str(style='brackets')
'[0.099999999999999991 .. 0.70000000000000007]'
sage: nearest = RIF(RR(1/10), RR(7/10)); nearest.str(style='brackets')
'[0.10000000000000000 .. 0.69999999999999996]'
sage: nearest.lower() - outward.lower()
1.38777878078144e-17
sage: outward.upper() - nearest.upper()
1.11022302462516e-16
Some examples with a real interval field of higher precision::
sage: R = RealIntervalField(100)
sage: R(3)
3
sage: R(R(3))
3
sage: R(pi)
3.14159265358979323846264338328?
sage: R(-2/19)
-0.1052631578947368421052631578948?
sage: R(e,pi).str(style='brackets')
'[2.7182818284590452353602874713512 .. 3.1415926535897932384626433832825]'
TESTS::
sage: RIF._lower_field() is RealField(53, rnd='RNDD')
True
sage: RIF._upper_field() is RealField(53, rnd='RNDU')
True
sage: RIF._middle_field() is RR
True
sage: TestSuite(RIF).run()
"""
def __init__(self, int prec=53, int sci_not=0):
"""
Initialize ``self``.
EXAMPLES::
sage: RealIntervalField()
Real Interval Field with 53 bits of precision
sage: RealIntervalField(200)
Real Interval Field with 200 bits of precision
"""
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
self.sci_not = sci_not
self.__lower_field = RealField(prec, sci_not, "RNDD")
self.__middle_field = RealField(prec, sci_not, "RNDN")
self.__upper_field = RealField(prec, sci_not, "RNDU")
from sage.categories.fields import Fields
ParentWithGens.__init__(self, self, tuple([]), False, category = Fields())
def _lower_field(self):
"""
Return the :class:`RealField_class` with rounding mode ``'RNDD'``
(rounding towards minus infinity).
EXAMPLES::
sage: RIF._lower_field()
Real Field with 53 bits of precision and rounding RNDD
sage: RealIntervalField(200)._lower_field()
Real Field with 200 bits of precision and rounding RNDD
"""
return self.__lower_field
def _middle_field(self):
"""
Return the :class:`RealField_class` with rounding mode ``'RNDN'``
(rounding towards nearest).
EXAMPLES::
sage: RIF._middle_field()
Real Field with 53 bits of precision
sage: RealIntervalField(200)._middle_field()
Real Field with 200 bits of precision
"""
return self.__middle_field
def _upper_field(self):
"""
Return the :class:`RealField_class` with rounding mode ``'RNDU'``
(rounding towards plus infinity).
EXAMPLES::
sage: RIF._upper_field()
Real Field with 53 bits of precision and rounding RNDU
sage: RealIntervalField(200)._upper_field()
Real Field with 200 bits of precision and rounding RNDU
"""
return self.__upper_field
def _real_field(self, rnd):
"""
Return the :class:`RealField_class` with rounding mode ``rnd``.
EXAMPLES::
sage: RIF._real_field('RNDN')
Real Field with 53 bits of precision
sage: RIF._real_field('RNDZ')
Real Field with 53 bits of precision and rounding RNDZ
sage: RealIntervalField(200)._real_field('RNDD')
Real Field with 200 bits of precision and rounding RNDD
"""
if rnd == "RNDD":
return self._lower_field()
elif rnd == "RNDN":
return self._middle_field()
elif rnd == "RNDU":
return self._upper_field()
else:
return RealField(self.__prec, self.sci_not, "RNDZ")
cdef RealIntervalFieldElement _new(self):
"""
Return a new real number with parent ``self``.
"""
cdef RealIntervalFieldElement x
x = PY_NEW(RealIntervalFieldElement)
x._parent = self
mpfi_init2(x.value, self.__prec)
x.init = 1
return x
def _repr_(self):
"""
Return a string representation of ``self``.
EXAMPLES::
sage: RealIntervalField() # indirect doctest
Real Interval Field with 53 bits of precision
sage: RealIntervalField(200) # indirect doctest
Real Interval Field with 200 bits of precision
"""
s = "Real Interval Field with %s bits of precision"%self.__prec
return s
def _latex_(self):
r"""
LaTeX representation for the real interval field.
EXAMPLES::
sage: latex(RIF) # indirect doctest
\Bold{I} \Bold{R}
"""
return "\\Bold{I} \\Bold{R}"
def _sage_input_(self, sib, coerce):
r"""
Produce an expression which will reproduce this value when evaluated.
EXAMPLES::
sage: sage_input(RIF, verify=True)
# Verified
RIF
sage: sage_input(RealIntervalField(25), verify=True)
# Verified
RealIntervalField(25)
sage: k = (RIF, RealIntervalField(37), RealIntervalField(1024))
sage: sage_input(k, verify=True)
# Verified
(RIF, RealIntervalField(37), RealIntervalField(1024))
sage: sage_input((k, k), verify=True)
# Verified
RIF37 = RealIntervalField(37)
RIF1024 = RealIntervalField(1024)
((RIF, RIF37, RIF1024), (RIF, RIF37, RIF1024))
sage: from sage.misc.sage_input import SageInputBuilder
sage: RealIntervalField(2)._sage_input_(SageInputBuilder(), False)
{call: {atomic:RealIntervalField}({atomic:2})}
"""
if self.prec() == 53:
return sib.name('RIF')
v = sib.name('RealIntervalField')(sib.int(self.prec()))
name = 'RIF%d' % self.prec()
sib.cache(self, v, name)
return v
cpdef bint is_exact(self) except -2:
"""
Returns whether or not this field is exact, which is always ``False``.
EXAMPLES::
sage: RIF.is_exact()
False
"""
return False
def __call__(self, x, y=None, int base=10):
"""
Create an element in this real interval field.
INPUT:
- ``x`` - a number, string, or 2-tuple
- ``y`` - (default: ``None``); if given ``x`` is set to ``(x,y)``;
this is so you can write ``R(2,3)`` to make the interval from 2 to 3
- ``base`` - integer (default: 10) - only used if ``x`` is a string
OUTPUT: an element of this real interval field.
EXAMPLES::
sage: R = RealIntervalField(20)
sage: R('1.234')
1.23400?
sage: R('2', base=2)
Traceback (most recent call last):
...
TypeError: Unable to convert number to real interval.
sage: a = R('1.1001', base=2); a
1.5625000?
sage: a.str(2)
'1.1001000000000000000?'
Type: RealIntervalField? for more information.
"""
if not y is None:
x = (x,y)
return RealIntervalFieldElement(self, x, base)
def construction(self):
r"""
Returns the functorial construction of ``self``, namely, completion of
the rational numbers with respect to the prime at `\infty`,
and the note that this is an interval field.
Also preserves other information that makes this field unique (e.g.
precision, print mode).
EXAMPLES::
sage: R = RealIntervalField(123)
sage: c, S = R.construction(); S
Rational Field
sage: R == c(S)
True
"""
from sage.categories.pushout import CompletionFunctor
return (CompletionFunctor(sage.rings.infinity.Infinity,
self.prec(),
{'sci_not': self.scientific_notation(), 'type': 'Interval'}),
sage.rings.rational_field.QQ)
cdef _coerce_c_impl(self, x):
"""
Canonical coercion of ``x`` to this mpfi real field.
The rings that canonically coerce to this mpfi real field are:
- this mpfi field itself
- any mpfr real field with precision that is as large as this
one
- any other mpfi real field with precision that is as large as
this one
- anything that canonically coerces to the mpfr real field
with same precision as ``self``.
Values which can be exactly represented as a floating-point number
are coerced to a precise interval, with upper and lower bounds
equal; otherwise, the upper and lower bounds will typically be
adjacent floating-point numbers that surround the given value.
"""
if isinstance(x, real_mpfr.RealNumber):
P = x.parent()
if (<RealField_class> P).__prec >= self.__prec:
return self(x)
else:
raise TypeError, "Canonical coercion from lower to higher precision not defined"
if isinstance(x, RealIntervalFieldElement):
P = x.parent()
if (<RealIntervalField_class> P).__prec >= self.__prec:
return self(x)
else:
raise TypeError, "Canonical coercion from lower to higher precision not defined"
if isinstance(x, (Integer, Rational)):
return self(x)
cdef RealNumber lower, upper
try:
lower = self.__lower_field._coerce_(x)
upper = self.__upper_field._coerce_(x)
return self(lower, upper)
except TypeError as msg:
raise TypeError, "no canonical coercion of element into self"
def __cmp__(self, other):
"""
Compare ``self`` to ``other``.
EXAMPLES::
sage: RealIntervalField(10) == RealIntervalField(11)
False
sage: RealIntervalField(10) == RealIntervalField(10)
True
sage: RealIntervalField(10,sci_not=True) == RealIntervalField(10,sci_not=False)
True
sage: RealIntervalField(10) == IntegerRing()
False
"""
if not isinstance(other, RealIntervalField_class):
return -1
cdef RealIntervalField_class _other
_other = other # to access C structure
if self.__prec == _other.__prec:
return 0
return 1
def __reduce__(self):
"""
For pickling.
EXAMPLES::
sage: R = RealIntervalField(sci_not=1, prec=200)
sage: loads(dumps(R)) == R
True
"""
return __create__RealIntervalField_version0, (self.__prec, self.sci_not)
def random_element(self, *args, **kwds):
"""
Return a random element of ``self``. Any arguments or keywords are
passed onto the random element function in real field.
By default, this is uniformly distributed in `[-1, 1]`.
EXAMPLES::
sage: RIF.random_element()
0.15363619378561300?
sage: RIF.random_element()
-0.50298737524751780?
sage: RIF.random_element(-100, 100)
60.958996432224126?
Passes extra positional or keyword arguments through::
sage: RIF.random_element(min=0, max=100)
2.5572702830891970?
sage: RIF.random_element(min=-100, max=0)
-1.5803457307118123?
"""
return self(self._middle_field().random_element(*args, **kwds))
def gen(self, i=0):
"""
Return the ``i``-th generator of ``self``.
EXAMPLES::
sage: RIF.gen(0)
1
sage: RIF.gen(1)
Traceback (most recent call last):
...
IndexError: self has only one generator
"""
if i == 0:
return self(1)
else:
raise IndexError("self has only one generator")
def complex_field(self):
"""
Return complex field of the same precision.
EXAMPLES::
sage: RIF.complex_field()
Complex Interval Field with 53 bits of precision
"""
return sage.rings.complex_interval_field.ComplexIntervalField(self.prec())
def ngens(self):
"""
Return the number of generators of ``self``, which is 1.
EXAMPLES::
sage: RIF.ngens()
1
"""
return 1
def gens(self):
"""
Return a list of generators.
EXAMPLE::
sage: RIF.gens()
[1]
"""
return [self.gen()]
def _is_valid_homomorphism_(self, codomain, im_gens):
"""
Return ``True`` if the map from ``self`` to ``codomain`` sending
``self(1)`` to the unique element of ``im_gens`` is a valid field
homomorphism. Otherwise, return ``False``.
EXAMPLES::
sage: RIF._is_valid_homomorphism_(RDF,[RDF(1)])
False
sage: RIF._is_valid_homomorphism_(CIF,[CIF(1)])
True
sage: RIF._is_valid_homomorphism_(CIF,[CIF(-1)])
False
sage: R=RealIntervalField(100)
sage: RIF._is_valid_homomorphism_(R,[R(1)])
False
sage: RIF._is_valid_homomorphism_(CC,[CC(1)])
False
sage: RIF._is_valid_homomorphism_(GF(2),GF(2)(1))
False
"""
try:
s = codomain._coerce_(self(1))
except TypeError:
return False
return s == im_gens[0]
def _repr_option(self, key):
"""
Metadata about the :meth:`_repr_` output.
See :meth:`sage.structure.parent._repr_option` for details.
EXAMPLES::
sage: RealIntervalField(10)._repr_option('element_is_atomic')
True
"""
if key == 'element_is_atomic':
return True
return super(RealIntervalField_class, self)._repr_option(key)
def is_finite(self):
"""
Return ``False``, since the field of real numbers is not finite.
EXAMPLES::
sage: RealIntervalField(10).is_finite()
False
"""
return False
def characteristic(self):
"""
Returns 0, since the field of real numbers has characteristic 0.
EXAMPLES::
sage: RealIntervalField(10).characteristic()
0
"""
return Integer(0)
def name(self):
"""
Return the name of ``self``.
EXAMPLES::
sage: RIF.name()
'IntervalRealIntervalField53'
sage: RealIntervalField(200).name()
'IntervalRealIntervalField200'
"""
return "IntervalRealIntervalField%s"%(self.__prec)
def __hash__(self):
"""
Return the hash value of ``self``.
EXAMPLES::
sage: hash(RIF) == hash(RealIntervalField(53)) # indirect doctest
True
sage: hash(RealIntervalField(200)) == hash(RealIntervalField(200))
True
"""
return hash(self.name())
def precision(self):
"""
Return the precision of this field (in bits).
EXAMPLES::
sage: RIF.precision()
53
sage: RealIntervalField(200).precision()
200
"""
return self.__prec
prec = precision
def to_prec(self, prec):
"""
Returns a real interval field to the given precision.
EXAMPLES::
sage: RIF.to_prec(200)
Real Interval Field with 200 bits of precision
sage: RIF.to_prec(20)
Real Interval Field with 20 bits of precision
sage: RIF.to_prec(53) is RIF
True
"""
return RealIntervalField(prec)
def _magma_init_(self, magma):
r"""
Return a string representation of ``self`` in the Magma language.
EXAMPLES::
sage: magma(RealIntervalField(80)) # optional - magma # indirect doctest
Real field of precision 24
sage: floor(RR(log(2**80, 10)))
24
"""
return "RealField(%s : Bits := true)" % self.prec()
def pi(self):
r"""
Returns `\pi` to the precision of this field.
EXAMPLES::
sage: R = RealIntervalField(100)
sage: R.pi()
3.14159265358979323846264338328?
sage: R.pi().sqrt()/2
0.88622692545275801364908374167?
sage: R = RealIntervalField(150)