-
-
Notifications
You must be signed in to change notification settings - Fork 405
/
real_mpfr.pyx
5989 lines (4901 loc) · 183 KB
/
real_mpfr.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 Numbers
AUTHORS:
- Kyle Schalm (2005-09)
- William Stein: bug fixes, examples, maintenance
- Didier Deshommes (2006-03-19): examples
- David Harvey (2006-09-20): compatibility with Element._parent
- William Stein (2006-10): default printing truncates to avoid base-2
rounding confusing (fix suggested by Bill Hart)
- Didier Deshommes: special constructor for QD numbers
- Paul Zimmermann (2008-01): added new functions from mpfr-2.3.0,
replaced some, e.g., sech = 1/cosh, by their original mpfr version.
- Carl Witty (2008-02): define floating-point rank and associated
functions; add some documentation
- Robert Bradshaw (2009-09): decimal literals, optimizations
- Jeroen Demeyer (2012-05-27): set the MPFR exponent range to the
maximal possible value (:trac:`13033`)
- Travis Scrimshaw (2012-11-02): Added doctests for full coverage
- Eviatar Bach (2013-06): Fixing numerical evaluation of log_gamma
- Vincent Klein (2017-06): RealNumber constructor support gmpy2.mpfr
, gmpy2.mpq or gmpy2.mpz parameter.
Add __mpfr__ to class RealNumber.
This is a binding for the MPFR arbitrary-precision floating point
library.
We define a class :class:`RealField`, where each instance of
:class:`RealField` specifies a field of floating-point
numbers with a specified precision and rounding mode. Individual
floating-point numbers are of :class:`RealNumber`.
In Sage (as in MPFR), floating-point numbers of precision
`p` are of the form `s m 2^{e-p}`, where
`s \in \{-1, 1\}`, `2^{p-1} \leq m < 2^p`, and
`-2^B + 1 \leq e \leq 2^B - 1` where `B = 30` on 32-bit systems
and `B = 62` on 64-bit systems;
additionally, there are the special values ``+0``, ``-0``,
``+infinity``, ``-infinity`` and ``NaN`` (which stands for Not-a-Number).
Operations in this module which are direct wrappers of MPFR
functions are "correctly rounded"; we briefly describe what this
means. Assume that you could perform the operation exactly, on real
numbers, to get a result `r`. If this result can be
represented as a floating-point number, then we return that
number.
Otherwise, the result `r` is between two floating-point
numbers. For the directed rounding modes (round to plus infinity,
round to minus infinity, round to zero), we return the
floating-point number in the indicated direction from `r`.
For round to nearest, we return the floating-point number which is
nearest to `r`.
This leaves one case unspecified: in round to nearest mode, what
happens if `r` is exactly halfway between the two nearest
floating-point numbers? In that case, we round to the number with
an even mantissa (the mantissa is the number `m` in the
representation above).
Consider the ordered set of floating-point numbers of precision
`p`. (Here we identify ``+0`` and
``-0``, and ignore ``NaN``.) We can give a
bijection between these floating-point numbers and a segment of the
integers, where 0 maps to 0 and adjacent floating-point numbers map
to adjacent integers. We call the integer corresponding to a given
floating-point number the "floating-point rank" of the number.
(This is not standard terminology; I just made it up.)
EXAMPLES:
A difficult conversion::
sage: RR(sys.maxsize)
9.22337203685478e18 # 64-bit
2.14748364700000e9 # 32-bit
TESTS::
sage: -1e30
-1.00000000000000e30
sage: (-1. + 2^-52).hex()
'-0xf.ffffffffffffp-4'
Make sure we don't have a new field for every new literal::
sage: parent(2.0) is parent(2.0)
True
sage: RealField(100, rnd='RNDZ') is RealField(100, rnd='RNDD')
False
sage: RealField(100, rnd='RNDZ') is RealField(100, rnd='RNDZ')
True
sage: RealField(100, rnd='RNDZ') is RealField(100, rnd=1)
True
"""
#*****************************************************************************
# Copyright (C) 2005-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.
# https://www.gnu.org/licenses/
#*****************************************************************************
import math # for log
import sys
import re
from cpython.object cimport Py_NE, Py_EQ
from cysignals.signals cimport sig_on, sig_off
from sage.ext.stdsage cimport PY_NEW
from sage.libs.gmp.pylong cimport mpz_set_pylong
from sage.libs.gmp.mpz cimport *
from sage.libs.mpfr cimport *
from sage.misc.randstate cimport randstate, current_randstate
from sage.cpython.string cimport char_to_str, str_to_bytes
from sage.misc.superseded import deprecation
from sage.structure.element cimport RingElement, Element, ModuleElement
from sage.structure.richcmp cimport rich_to_bool_sgn, rich_to_bool
cdef bin_op
from sage.structure.element import bin_op
import sage.misc.weak_dict
import operator
from cypari2.paridecl cimport *
from cypari2.gen cimport Gen
from cypari2.stack cimport new_gen
from sage.libs.mpmath.utils cimport mpfr_to_mpfval
from .integer cimport Integer
from .rational cimport Rational
from sage.categories.map cimport Map
cdef ZZ, QQ, RDF
from .integer_ring import ZZ
from .rational_field import QQ
from .real_double import RDF
from .real_double cimport RealDoubleElement
import sage.rings.rational_field
import sage.rings.infinity
from sage.structure.parent_gens cimport ParentWithGens
from sage.arith.numerical_approx cimport digits_to_bits
from sage.arith.constants cimport M_LN2_LN10
from sage.arith.long cimport is_small_python_int
cimport gmpy2
gmpy2.import_gmpy2()
#*****************************************************************************
#
# Implementation
#
#*****************************************************************************
_re_skip_zeroes = re.compile(r'^(.+?)0*$')
cdef object numpy_double_interface = {'typestr': '=f8'}
cdef object numpy_object_interface = {'typestr': '|O'}
# Avoid signal handling for cheap operations when the
# precision is below this threshold.
cdef enum:
SIG_PREC_THRESHOLD = 1000
#*****************************************************************************
#
# External Python access to constants
#
#*****************************************************************************
def mpfr_prec_min():
"""
Return the mpfr variable ``MPFR_PREC_MIN``.
EXAMPLES::
sage: from sage.rings.real_mpfr import mpfr_prec_min
sage: mpfr_prec_min()
1
sage: R = RealField(2)
sage: R(2) + R(1)
3.0
sage: R(4) + R(1)
4.0
sage: R = RealField(0)
Traceback (most recent call last):
...
ValueError: prec (=0) must be >= 1 and <= 2147483391
"""
return MPFR_PREC_MIN
# see Trac #11666 for the origin of this magical constant
cdef int MY_MPFR_PREC_MAX = 2147483647 - 256 # = 2^31-257
def mpfr_prec_max():
"""
TESTS::
sage: from sage.rings.real_mpfr import mpfr_prec_max
sage: mpfr_prec_max()
2147483391
sage: R = RealField(2^31-257)
sage: R
Real Field with 2147483391 bits of precision
sage: R = RealField(2^31-256)
Traceback (most recent call last):
...
ValueError: prec (=2147483392) must be >= 1 and <= 2147483391
"""
global MY_MPFR_PREC_MAX
return MY_MPFR_PREC_MAX
def mpfr_get_exp_min():
"""
Return the current minimal exponent for MPFR numbers.
EXAMPLES::
sage: from sage.rings.real_mpfr import mpfr_get_exp_min
sage: mpfr_get_exp_min()
-1073741823 # 32-bit
-4611686018427387903 # 64-bit
sage: 0.5 >> (-mpfr_get_exp_min())
2.38256490488795e-323228497 # 32-bit
8.50969131174084e-1388255822130839284 # 64-bit
sage: 0.5 >> (-mpfr_get_exp_min()+1)
0.000000000000000
"""
return mpfr_get_emin()
def mpfr_get_exp_max():
"""
Return the current maximal exponent for MPFR numbers.
EXAMPLES::
sage: from sage.rings.real_mpfr import mpfr_get_exp_max
sage: mpfr_get_exp_max()
1073741823 # 32-bit
4611686018427387903 # 64-bit
sage: 0.5 << mpfr_get_exp_max()
1.04928935823369e323228496 # 32-bit
2.93782689455579e1388255822130839282 # 64-bit
sage: 0.5 << (mpfr_get_exp_max()+1)
+infinity
"""
return mpfr_get_emax()
def mpfr_set_exp_min(mp_exp_t e):
"""
Set the minimal exponent for MPFR numbers.
EXAMPLES::
sage: from sage.rings.real_mpfr import mpfr_get_exp_min, mpfr_set_exp_min
sage: old = mpfr_get_exp_min()
sage: mpfr_set_exp_min(-1000)
sage: 0.5 >> 1000
4.66631809251609e-302
sage: 0.5 >> 1001
0.000000000000000
sage: mpfr_set_exp_min(old)
sage: 0.5 >> 1001
2.33315904625805e-302
"""
if mpfr_set_emin(e) != 0:
raise OverflowError("bad value for mpfr_set_exp_min()")
def mpfr_set_exp_max(mp_exp_t e):
"""
Set the maximal exponent for MPFR numbers.
EXAMPLES::
sage: from sage.rings.real_mpfr import mpfr_get_exp_max, mpfr_set_exp_max
sage: old = mpfr_get_exp_max()
sage: mpfr_set_exp_max(1000)
sage: 0.5 << 1000
5.35754303593134e300
sage: 0.5 << 1001
+infinity
sage: mpfr_set_exp_max(old)
sage: 0.5 << 1001
1.07150860718627e301
"""
if mpfr_set_emax(e) != 0:
raise OverflowError("bad value for mpfr_set_exp_max()")
def mpfr_get_exp_min_min():
"""
Get the minimal value allowed for :func:`mpfr_set_exp_min`.
EXAMPLES::
sage: from sage.rings.real_mpfr import mpfr_get_exp_min_min, mpfr_set_exp_min
sage: mpfr_get_exp_min_min()
-1073741823 # 32-bit
-4611686018427387903 # 64-bit
This is really the minimal value allowed::
sage: mpfr_set_exp_min(mpfr_get_exp_min_min() - 1)
Traceback (most recent call last):
...
OverflowError: bad value for mpfr_set_exp_min()
"""
return mpfr_get_emin_min()
def mpfr_get_exp_max_max():
"""
Get the maximal value allowed for :func:`mpfr_set_exp_max`.
EXAMPLES::
sage: from sage.rings.real_mpfr import mpfr_get_exp_max_max, mpfr_set_exp_max
sage: mpfr_get_exp_max_max()
1073741823 # 32-bit
4611686018427387903 # 64-bit
This is really the maximal value allowed::
sage: mpfr_set_exp_max(mpfr_get_exp_max_max() + 1)
Traceback (most recent call last):
...
OverflowError: bad value for mpfr_set_exp_max()
"""
return mpfr_get_emax_max()
# On Sage startup, set the exponent range to the maximum allowed
mpfr_set_exp_min(mpfr_get_emin_min())
mpfr_set_exp_max(mpfr_get_emax_max())
#*****************************************************************************
#
# Real Field
#
#*****************************************************************************
# The real field is in Cython, so mpfr elements will have access to
# their parent via direct C calls, which will be faster.
from sage.arith.long cimport (pyobject_to_long, integer_check_long_py,
ERR_OVERFLOW)
cdef dict rounding_modes = dict(RNDN=MPFR_RNDN, RNDZ=MPFR_RNDZ,
RNDD=MPFR_RNDD, RNDU=MPFR_RNDU, RNDA=MPFR_RNDA, RNDF=MPFR_RNDF)
cdef double LOG_TEN_TWO_PLUS_EPSILON = 3.321928094887363 # a small overestimate of log(10,2)
cdef object RealField_cache = sage.misc.weak_dict.WeakValueDictionary()
cpdef RealField(int prec=53, int sci_not=0, rnd=MPFR_RNDN):
"""
RealField(prec, sci_not, rnd):
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:`mpfr_prec_min()` and :func:`mpfr_prec_max()`. In the current
implementation, :func:`mpfr_prec_min()` is equal to 2.
- ``sci_not`` -- (default: ``False``) if ``True``, always display using
scientific notation; if ``False``, display using scientific notation
only for very large or very small numbers
- ``rnd`` -- (string) the rounding mode:
- ``'RNDN'`` -- (default) round to nearest (ties go to the even
number): Knuth says this is the best choice to prevent "floating
point drift"
- ``'RNDD'`` -- round towards minus infinity
- ``'RNDZ'`` -- round towards zero
- ``'RNDU'`` -- round towards plus infinity
- ``'RNDA'`` -- round away from zero
- ``'RNDF'`` -- faithful rounding (currently experimental; not
guaranteed correct for every operation)
- for specialized applications, the rounding mode can also be
given as an integer value of type ``mpfr_rnd_t``. However, the
exact values are unspecified.
EXAMPLES::
sage: RealField(10)
Real Field with 10 bits of precision
sage: RealField()
Real Field with 53 bits of precision
sage: RealField(100000)
Real Field with 100000 bits of precision
Here we show the effect of rounding::
sage: R17d = RealField(17,rnd='RNDD')
sage: a = R17d(1)/R17d(3); a.exact_rational()
87381/262144
sage: R17u = RealField(17,rnd='RNDU')
sage: a = R17u(1)/R17u(3); a.exact_rational()
43691/131072
.. NOTE::
The default precision is 53, since according to the MPFR
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.'
"""
# We allow specifying the rounding mode as string or integer.
# But we pass an integer to __init__
cdef long r
try:
r = pyobject_to_long(rnd)
except TypeError:
try:
r = rounding_modes[rnd]
except KeyError:
raise ValueError("rounding mode (={!r}) must be one of {}".format(rnd,
sorted(rounding_modes)))
try:
return RealField_cache[prec, sci_not, r]
except KeyError:
R = RealField_class(prec=prec, sci_not=sci_not, rnd=r)
RealField_cache[prec, sci_not, r] = R
return R
cdef class RealField_class(sage.rings.ring.Field):
"""
An approximation to the field of real numbers using floating point
numbers with any specified precision. Answers derived from
calculations in this approximation may differ from what they would
be if those calculations were performed in the true field of real
numbers. This is due to the rounding errors inherent to finite
precision calculations.
See the documentation for the module :mod:`sage.rings.real_mpfr` for more
details.
"""
def __init__(self, int prec=53, int sci_not=0, long rnd=MPFR_RNDN):
"""
Initialize ``self``.
EXAMPLES::
sage: RealField()
Real Field with 53 bits of precision
sage: RealField(100000)
Real Field with 100000 bits of precision
sage: RealField(17,rnd='RNDD')
Real Field with 17 bits of precision and rounding RNDD
TESTS:
Test the various rounding modes::
sage: RealField(100, rnd="RNDN")
Real Field with 100 bits of precision
sage: RealField(100, rnd="RNDZ")
Real Field with 100 bits of precision and rounding RNDZ
sage: RealField(100, rnd="RNDU")
Real Field with 100 bits of precision and rounding RNDU
sage: RealField(100, rnd="RNDD")
Real Field with 100 bits of precision and rounding RNDD
sage: RealField(100, rnd="RNDA")
Real Field with 100 bits of precision and rounding RNDA
sage: RealField(100, rnd="RNDF")
Real Field with 100 bits of precision and rounding RNDF
sage: RealField(100, rnd=0)
Real Field with 100 bits of precision
sage: RealField(100, rnd=1)
Real Field with 100 bits of precision and rounding RNDZ
sage: RealField(100, rnd=2)
Real Field with 100 bits of precision and rounding RNDU
sage: RealField(100, rnd=3)
Real Field with 100 bits of precision and rounding RNDD
sage: RealField(100, rnd=4)
Real Field with 100 bits of precision and rounding RNDA
sage: RealField(100, rnd=5)
Real Field with 100 bits of precision and rounding RNDF
sage: RealField(100, rnd=3.14)
Traceback (most recent call last):
...
ValueError: rounding mode (=3.14000000000000) must be one of ['RNDA', 'RNDD', 'RNDF', 'RNDN', 'RNDU', 'RNDZ']
sage: RealField(100, rnd=6)
Traceback (most recent call last):
...
ValueError: unknown rounding mode 6
sage: RealField(100, rnd=10^100)
Traceback (most recent call last):
...
OverflowError: Sage Integer too large to convert to C long
Check methods inherited from categories::
sage: RealField(10).is_finite()
False
"""
global MY_MPFR_PREC_MAX
if prec < MPFR_PREC_MIN or prec > MY_MPFR_PREC_MAX:
raise ValueError("prec (=%s) must be >= %s and <= %s" % (
prec, MPFR_PREC_MIN, MY_MPFR_PREC_MAX))
self.__prec = prec
self.sci_not = sci_not
self.rnd = <mpfr_rnd_t>rnd
cdef const char* rnd_str = mpfr_print_rnd_mode(self.rnd)
if rnd_str is NULL:
raise ValueError("unknown rounding mode {}".format(rnd))
self.rnd_str = char_to_str(rnd_str + 5) # Strip "MPFR_"
from sage.categories.fields import Fields
ParentWithGens.__init__(self, self, tuple([]), False, category=Fields().Infinite().Metric().Complete())
# Initialize zero and one
cdef RealNumber rn
rn = self._new()
mpfr_set_zero(rn.value, 1)
self._zero_element = rn
rn = self._new()
mpfr_set_ui(rn.value, 1, MPFR_RNDZ)
self._one_element = rn
self._populate_coercion_lists_(convert_method_name='_mpfr_')
def _repr_(self):
"""
Return a string representation of ``self``.
EXAMPLES::
sage: RealField() # indirect doctest
Real Field with 53 bits of precision
sage: RealField(100000) # indirect doctest
Real Field with 100000 bits of precision
sage: RealField(17,rnd='RNDD') # indirect doctest
Real Field with 17 bits of precision and rounding RNDD
"""
s = "Real Field with %s bits of precision"%self.__prec
if self.rnd != MPFR_RNDN:
s = s + " and rounding %s"%(self.rnd_str)
return s
def _latex_(self):
r"""
Return a latex representation of ``self``.
EXAMPLES::
sage: latex(RealField()) # indirect doctest
\Bold{R}
"""
return "\\Bold{R}"
def _sage_input_(self, sib, coerce):
r"""
Produce an expression which will reproduce this value when
evaluated.
EXAMPLES::
sage: sage_input(RR, verify=True)
# Verified
RR
sage: sage_input(RealField(25, rnd='RNDZ'), verify=True)
# Verified
RealField(25, rnd='RNDZ')
sage: k = (RR, RealField(75, rnd='RNDU'), RealField(13))
sage: sage_input(k, verify=True)
# Verified
(RR, RealField(75, rnd='RNDU'), RealField(13))
sage: sage_input((k, k), verify=True)
# Verified
RR75u = RealField(75, rnd='RNDU')
RR13 = RealField(13)
((RR, RR75u, RR13), (RR, RR75u, RR13))
sage: from sage.misc.sage_input import SageInputBuilder
sage: RealField(99, rnd='RNDD')._sage_input_(SageInputBuilder(), False)
{call: {atomic:RealField}({atomic:99}, rnd={atomic:'RNDD'})}
"""
if self.rnd == MPFR_RNDN and self.prec() == 53:
return sib.name('RR')
if self.rnd != MPFR_RNDN:
rnd_abbrev = self.rnd_str[-1:].lower()
v = sib.name('RealField')(sib.int(self.prec()), rnd=self.rnd_str)
else:
rnd_abbrev = ''
v = sib.name('RealField')(sib.int(self.prec()))
name = 'RR%d%s' % (self.prec(), rnd_abbrev)
sib.cache(self, v, name)
return v
cpdef bint is_exact(self) except -2:
"""
Return ``False``, since a real field (represented using finite
precision) is not exact.
EXAMPLES::
sage: RR.is_exact()
False
sage: RealField(100).is_exact()
False
"""
return False
def _element_constructor_(self, x, base=10):
"""
Coerce ``x`` into this real field.
EXAMPLES::
sage: R = RealField(20)
sage: R('1.234')
1.2340
sage: R('2', base=2)
Traceback (most recent call last):
...
TypeError: unable to convert '2' to a real number
sage: a = R('1.1001', base=2); a
1.5625
sage: a.str(2)
'1.1001000000000000000'
sage: R(oo)
+infinity
sage: R(unsigned_infinity)
Traceback (most recent call last):
...
ValueError: can only convert signed infinity to RR
sage: R(CIF(NaN))
NaN
sage: R(complex(1.7))
1.7000
"""
if hasattr(x, '_mpfr_'):
return x._mpfr_(self)
cdef RealNumber z
z = self._new()
z._set(x, base)
return z
cpdef _coerce_map_from_(self, S):
"""
Canonical coercion of x to this MPFR real field.
The rings that canonically coerce to this MPFR real field are:
- Any MPFR real field with precision that is as large as this one
- int, long, integer, and rational rings.
- the field of algebraic reals
- floats and RDF if self.prec = 53
EXAMPLES::
sage: RR.has_coerce_map_from(ZZ) # indirect doctest
True
sage: RR.has_coerce_map_from(float)
True
sage: RealField(100).has_coerce_map_from(float)
False
sage: RR.has_coerce_map_from(RealField(200))
True
sage: RR.has_coerce_map_from(RealField(20))
False
sage: RR.has_coerce_map_from(RDF)
True
sage: RR.coerce_map_from(ZZ)(2)
2.00000000000000
sage: RR.coerce(3.4r)
3.40000000000000
sage: RR.coerce(3.4)
3.40000000000000
sage: RR.coerce(3.4r)
3.40000000000000
sage: RR.coerce(3.400000000000000000000000000000000000000000)
3.40000000000000
sage: RealField(100).coerce(3.4)
Traceback (most recent call last):
...
TypeError: no canonical coercion from Real Field with 53 bits of precision to Real Field with 100 bits of precision
sage: RR.coerce(17/5)
3.40000000000000
sage: RR.coerce(2^4000)
1.31820409343094e1204
sage: RR.coerce_map_from(float)
Generic map:
From: Set of Python objects of class 'float'
To: Real Field with 53 bits of precision
TESTS::
sage: 1.0 - ZZ(1) - int(1) - long(1) - QQ(1) - RealField(100)(1) - AA(1) - RLF(1)
-6.00000000000000
sage: R = RR['x'] # Hold reference to avoid garbage collection, see Trac #24709
sage: R.get_action(ZZ)
Right scalar multiplication by Integer Ring on Univariate Polynomial Ring in x over Real Field with 53 bits of precision
"""
if S is ZZ:
return ZZtoRR(ZZ, self)
elif S is QQ:
return QQtoRR(QQ, self)
elif (S is RDF or S is float) and self.__prec <= 53:
return double_toRR(S, self)
elif S is long:
return int_toRR(long, self)
elif S is int:
return int_toRR(int, self)
elif isinstance(S, RealField_class) and S.prec() >= self.__prec:
return RRtoRR(S, self)
elif QQ.has_coerce_map_from(S):
return QQtoRR(QQ, self) * QQ._internal_coerce_map_from(S)
from sage.rings.qqbar import AA
from sage.rings.real_lazy import RLF
if S is AA or S is RLF:
return self.convert_method_map(S, "_mpfr_")
return self._coerce_map_via([RLF], S)
def __richcmp__(RealField_class self, other, int op):
"""
Compare two real fields, returning ``True`` if they are equivalent
and ``False`` if they are not.
EXAMPLES::
sage: RealField(10) == RealField(11)
False
sage: RealField(10) == RealField(10)
True
sage: RealField(10,rnd='RNDN') == RealField(10,rnd='RNDZ')
False
Scientific notation affects only printing, not mathematically how
the field works, so this does not affect equality testing::
sage: RealField(10,sci_not=True) == RealField(10,sci_not=False)
True
sage: RealField(10) == IntegerRing()
False
::
sage: RS = RealField(sci_not=True)
sage: RR == RS
True
sage: RS.scientific_notation(False)
sage: RR == RS
True
"""
if op != Py_EQ and op != Py_NE:
return NotImplemented
if not isinstance(other, RealField_class):
return NotImplemented
_other = <RealField_class>other # to access C structure
return (self.__prec == _other.__prec and
self.rnd == _other.rnd) == (op == Py_EQ)
def __reduce__(self):
"""
Return the arguments sufficient for pickling.
EXAMPLES::
sage: R = RealField(sci_not=1, prec=200, rnd='RNDU')
sage: loads(dumps(R)) == R
True
"""
return __create__RealField_version0, (self.__prec, self.sci_not, self.rnd_str)
def construction(self):
r"""
Return the functorial construction of ``self``, namely,
completion of the rational numbers with respect to the prime
at `\infty`.
Also preserves other information that makes this field unique (e.g.
precision, rounding, print mode).
EXAMPLES::
sage: R = RealField(100, rnd='RNDU')
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(),
{'type': 'MPFR', 'sci_not': self.scientific_notation(), 'rnd': self.rnd}),
sage.rings.rational_field.QQ)
def gen(self, i=0):
"""
Return the ``i``-th generator of ``self``.
EXAMPLES::
sage: R=RealField(100)
sage: R.gen(0)
1.0000000000000000000000000000
sage: R.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: RR.complex_field()
Complex Field with 53 bits of precision
sage: RR.complex_field() is CC
True
sage: RealField(100,rnd='RNDD').complex_field()
Complex Field with 100 bits of precision
sage: RealField(100).complex_field()
Complex Field with 100 bits of precision
"""
from sage.rings.complex_field import ComplexField
return ComplexField(self.prec())
def algebraic_closure(self):
"""
Return the algebraic closure of ``self``, i.e., the complex field with
the same precision.
EXAMPLES::
sage: RR.algebraic_closure()
Complex Field with 53 bits of precision
sage: RR.algebraic_closure() is CC
True
sage: RealField(100,rnd='RNDD').algebraic_closure()
Complex Field with 100 bits of precision
sage: RealField(100).algebraic_closure()
Complex Field with 100 bits of precision
"""
return self.complex_field()
def ngens(self):
"""
Return the number of generators.
EXAMPLES::
sage: RR.ngens()
1
"""
return 1
def gens(self):
"""
Return a list of generators.
EXAMPLES::
sage: RR.gens()
[1.00000000000000]
"""
return [self.gen()]
def _is_valid_homomorphism_(self, codomain, im_gens, base_map=None):
"""
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: RR._is_valid_homomorphism_(RDF,[RDF(1)])
True
sage: RR._is_valid_homomorphism_(CDF,[CDF(1)])
True
sage: RR._is_valid_homomorphism_(CDF,[CDF(-1)])
False
sage: R=RealField(100)
sage: RR._is_valid_homomorphism_(R,[R(1)])
False
sage: RR._is_valid_homomorphism_(CC,[CC(1)])
True
sage: RR._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: RealField(10)._repr_option('element_is_atomic')
True
"""
if key == 'element_is_atomic':
return True
return super(RealField_class, self)._repr_option(key)
def characteristic(self):
"""
Returns 0, since the field of real numbers has characteristic 0.
EXAMPLES::
sage: RealField(10).characteristic()
0
"""
return Integer(0)
def name(self):
"""
Return the name of ``self``, which encodes the precision and
rounding convention.
EXAMPLES::
sage: RR.name()
'RealField53_0'
sage: RealField(100,rnd='RNDU').name()
'RealField100_2'
"""
return "RealField%s_%s"%(self.__prec,self.rnd)
def __hash__(self):
"""
Returns a hash function of the field, which takes into account
the precision and rounding convention.
EXAMPLES::
sage: hash(RealField(100,rnd='RNDU')) == hash(RealField(100,rnd='RNDU'))
True
sage: hash(RR) == hash(RealField(53))
True
"""
return hash(self.name())
def precision(self):
"""
Return the precision of ``self``.
EXAMPLES::
sage: RR.precision()
53
sage: RealField(20).precision()
20
"""
return self.__prec
prec=precision # an alias
def _magma_init_(self, magma):
r"""
Return a string representation of ``self`` in the Magma language.