# Ticket #7682: trac-7682-realfield-printing-options.2.patch

File trac-7682-realfield-printing-options.2.patch, 57.4 KB (added by jason, 11 years ago)

apply instead of previous patch. Rebased to Sage 4.3.3

• ## sage/calculus/calculus.py

# HG changeset patch
# User Jason Grout <jason-sage@creativetrax.com>
# Date 1264426711 21600
# Node ID 5a0fc65a610385eebb944e8440a21fbe339e3263
# Parent  21f187597161a097055baf78bff2b340f1b67b89
Added a more comprehensive print options feature to RealField.

Fixed lots and lots of docstrings

Fixed the bug: RR('inf').is_unit() returns True

diff -r 21f187597161 -r 5a0fc65a6103 sage/calculus/calculus.py
 a elif epsilon and error < epsilon: return g elif algorithm is not None: raise NotImplementedError, "Could not prove minimal polynomial %s (epsilon %s)" % (g, RR(error).str(no_sci=False)) raise NotImplementedError, "Could not prove minimal polynomial %s (epsilon %s)" % (g, RR(error).str(scientific_notation='always')) if algorithm is not None: raise ValueError, "Could not find minimal polynomial (%s bits, degree %s)." % (bits, degree) search = sci_not.search(s) while not search is None: (start, end) = search.span() r = create_RealNumber(s[start:end]).str(no_sci=2, truncate=True) r = create_RealNumber(s[start:end]).str(scientific_notation='never', truncate=True) s = s.replace(s[start:end], r) search = sci_not.search(s)
• ## sage/calculus/desolvers.py

diff -r 21f187597161 -r 5a0fc65a6103 sage/calculus/desolvers.py
 a :: sage: RR = RealField(sci_not=0, prec=4, rnd='RNDU') sage: RR = RealField(prec=4, rnd='RNDU', print_options={'scientific_notation': 0}) sage: x,y = PolynomialRing(RR,2,"xy").gens() sage: eulers_method(5*x+y-5,0,1,1/2,1,method="None") [[0, 1], [1/2, -1.0], [1, -2.7], [3/2, -4.0]] :: sage: RR = RealField(sci_not=0, prec=4, rnd='RNDU') sage: RR = RealField(prec=4, rnd='RNDU', print_options={'scientific_notation': 0}) sage: x,y=PolynomialRing(RR,2,"xy").gens() sage: eulers_method(5*x+y-5,0,1,1/2,1) x                    y                  h*f(x,y) :: sage: RR = RealField(sci_not=0, prec=4, rnd='RNDU') sage: RR = RealField(prec=4, rnd='RNDU', print_options={'scientific_notation': 0}) sage: t,x,y=PolynomialRing(RR,3,"txy").gens() sage: f = x+y+t; g = x-y sage: eulers_method_2x2(f,g, 0, 0, 0, 1/3, 1) convert to a system: y_1' = y_2, y_1(0)=1; y_2' = \\frac{y_1-y_2}{1+t^2}, y_2(0)=-1.:: sage: RR = RealField(sci_not=0, prec=4, rnd='RNDU') sage: RR = RealField(prec=4, rnd='RNDU', print_options={'scientific_notation': 0}) sage: t, x, y=PolynomialRing(RR,3,"txy").gens() sage: f = y; g = (x-y)/(1+t^2) sage: eulers_method_2x2(f,g, 0, 1, -1, 1/4, 1)
• ## sage/misc/explain_pickle.py

diff -r 21f187597161 -r 5a0fc65a6103 sage/misc/explain_pickle.py
 a {('a', 'b'):[1r, 2r]} sage: explain_pickle(dumps(RR(pi)), in_current_sage=True) from sage.rings.real_mpfr import __create__RealNumber_version0 from sage.rings.real_mpfr import __create__RealField_version0 __create__RealNumber_version0(__create__RealField_version0(53r, False, 'RNDN'), '3.4gvml245kc0@0', 32r) from sage.rings.real_mpfr import __create__RealField_version1 __create__RealNumber_version0(__create__RealField_version1(53r, 'RNDN', {'scientific_notation':'extreme', 'skip_zeroes':False, 'truncate':True}), '3.4gvml245kc0@0', 32r) sage: s = 'hi' sage: explain_pickle(dumps((s, s))) ('hi', 'hi')
• ## sage/misc/latex.py

diff -r 21f187597161 -r 5a0fc65a6103 sage/misc/latex.py
 a sage: from sage.misc.latex import latex_extra_preamble sage: latex_extra_preamble() '\n\\newcommand{\\ZZ}{\\Bold{Z}}\n\\newcommand{\\RR}{\\Bold{R}}\n\\newcommand{\\CC}{\\Bold{C}}\n\\newcommand{\\QQ}{\\Bold{Q}}\n\\newcommand{\\QQbar}{\\overline{\\QQ}}\n\\newcommand{\\GF}[1]{\\Bold{F}_{#1}}\n\\newcommand{\\Zp}[1]{\\ZZ_{#1}}\n\\newcommand{\\Qp}[1]{\\QQ_{#1}}\n\\newcommand{\\Zmod}[1]{\\ZZ/#1\\ZZ}\n\\newcommand{\\CDF}{\\texttt{Complex Double Field}}\n\\newcommand{\\CIF}{\\Bold{C}}\n\\newcommand{\\CLF}{\\Bold{C}}\n\\newcommand{\\RDF}{\\Bold{R}}\n\\newcommand{\\RIF}{\\Bold{I} \\Bold{R}}\n\\newcommand{\\RLF}{\\Bold{R}}\n\\newcommand{\\CFF}{\\Bold{CFF}}\n\\newcommand{\\Bold}[1]{\\mathbf{#1}}\n' '\n\\newcommand{\\ZZ}{\\Bold{Z}}\n\\newcommand{\\RR}{\\Bold{R}^{}_{53}}\n\\newcommand{\\CC}{\\Bold{C}}\n\\newcommand{\\QQ}{\\Bold{Q}}\n\\newcommand{\\QQbar}{\\overline{\\QQ}}\n\\newcommand{\\GF}[1]{\\Bold{F}_{#1}}\n\\newcommand{\\Zp}[1]{\\ZZ_{#1}}\n\\newcommand{\\Qp}[1]{\\QQ_{#1}}\n\\newcommand{\\Zmod}[1]{\\ZZ/#1\\ZZ}\n\\newcommand{\\CDF}{\\texttt{Complex Double Field}}\n\\newcommand{\\CIF}{\\Bold{C}}\n\\newcommand{\\CLF}{\\Bold{C}}\n\\newcommand{\\RDF}{\\Bold{R}}\n\\newcommand{\\RIF}{\\Bold{I} \\Bold{R}}\n\\newcommand{\\RLF}{\\Bold{R}}\n\\newcommand{\\CFF}{\\Bold{CFF}}\n\\newcommand{\\Bold}[1]{\\mathbf{#1}}\n' """ from sage.misc.latex_macros import sage_latex_macros return (_Latex_prefs._option['preamble'] + "\n"
• ## sage/misc/misc.py

diff -r 21f187597161 -r 5a0fc65a6103 sage/misc/misc.py
 a should be replaced. - version - (optional) on which version and when the deprecation occured. Please put there the version of sageq at the time of deprecation. occured. Please put there the version of sage at the time of deprecation. EXAMPLES:: from sage.misc.lazy_attribute import lazy_attribute class DeprecatedFunctionAlias(object): """ A wrapper around methods or functions wich automatically print the correct A wrapper around methods or functions which automatically print the correct deprecation message. See :func:deprecated_function_alias. AUTHORS:
• ## sage/rings/real_interval_field.py

diff -r 21f187597161 -r 5a0fc65a6103 sage/rings/real_interval_field.py
 a return isinstance(x, RealIntervalFieldElementClass) def __reduce__RealIntervalField(prec, sci_not): return RealIntervalField(prec, sci_not) print_options={'scientific_notation': sci_not} return RealIntervalField(prec=prec, print_options=print_options) def __reduce__RealIntervalFieldElement(parent, x, base=10): return RealIntervalFieldElementClass(parent, x, base=base)
• ## sage/rings/real_mpfi.pxd

diff -r 21f187597161 -r 5a0fc65a6103 sage/rings/real_mpfi.pxd
 a cdef class RealIntervalField_class(sage.rings.ring.Field): cdef int __prec cdef bint sci_not cdef object print_options # Cache RealField instances for the lower, upper, and middle bounds. # These have the same precision as the interval field; # __lower_field rounds down, __upper_field rounds up.
• ## sage/rings/real_mpfi.pyx

diff -r 21f187597161 -r 5a0fc65a6103 sage/rings/real_mpfi.pyx
 a cimport real_mpfr from real_mpfr cimport RealField_class, RealNumber from real_mpfr import RealField from real_mpfr import RealField, sci_not_deprecation import real_mpfr import operator printing_style = 'question' printing_error_digits = 0 _PRINT_OPTIONS = {'skip_zeroes': False, 'truncate': True, 'scientific_notation': 'extreme', 'style': 'question', 'error_digits': 0} #***************************************************************************** # #       Real Field RealIntervalField_cache = {} def RealIntervalField(prec=53, sci_not=False): def RealIntervalField(prec=53, scientific_notation=None, print_options={},sci_not=None): r""" Construct a RealIntervalField_class, with caching. mpfr_prec_min() and mpfr_prec_max(). In the current implementation, mpfr_prec_min() is equal to 2. -  sci_not - (default: False) whether or not to display using scientific notation - scientific_notation - 'never' - never print using scientific notation; - 'extreme' (default) - print using scientific notation only for very large or very small numbers; - 'always' - always print with scientific notation; EXAMPLES:: sage: RealIntervalField() Real Interval Field with 53 bits of precision sage: RealIntervalField(200, sci_not=True) sage: RealIntervalField(200, scientific_notation=True) Real Interval Field with 200 bits of precision sage: RealIntervalField(53) is RIF True See the documentation for :class:RealIntervalField_class for many more examples. """ printing=_PRINT_OPTIONS.copy() printing.update(print_options) if sci_not is not None: from sage.misc.misc import deprecation deprecation("The sci_not keyword is deprecated.  Use print_options={'scientific_notation': %r} instead."%sci_not_deprecation[sci_not]) scientific_notation=sci_not_deprecation[sci_not] if scientific_notation is not None: printing['scientific_notation']=scientific_notation print_cached=tuple(sorted(printing.items())) try: return RealIntervalField_cache[prec, sci_not] return RealIntervalField_cache[prec, print_cached] except KeyError: RealIntervalField_cache[prec, sci_not] = R = RealIntervalField_class(prec, sci_not) RealIntervalField_cache[prec, print_cached] = R = RealIntervalField_class(prec=prec, print_options=printing, sci_not=sci_not) return R cdef class RealIntervalField_class(sage.rings.ring.Field): """ RealIntervalField(prec, sci_not): RealIntervalField(prec, scientific_notation): INPUT: implementation, mpfr_prec_min() is equal to 2. -  sci_not - (default: False) whether or not to display using -  scientific_notation - (default: False) whether or not to display using scientific notation EXAMPLES:: sage: RIF._middle_field() is RR True """ def __init__(self, int prec=53, int sci_not=0): def __init__(self, int prec=53, scientific_notation=None, print_options=None, sci_not=None): if sci_not is not None: from sage.misc.misc import deprecation deprecation("The sci_not keyword is deprecated.  Use scientific_notation instead.") scientific_notation=sci_not 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") self.print_options=_PRINT_OPTIONS.copy() if scientific_notation is not None: self.print_options['scientific_notation']=scientific_notation realfield_print_options={} for key in real_mpfr._PRINT_OPTIONS: if key in self.print_options: realfield_print_options[key]=self.print_options[key] self.__lower_field = RealField(prec=prec, rnd="RNDD", print_options=realfield_print_options) self.__middle_field = RealField(prec=prec, rnd="RNDN", print_options=realfield_print_options) self.__upper_field = RealField(prec=prec, rnd="RNDU", print_options=realfield_print_options) ParentWithGens.__init__(self, self, tuple([]), False) def _lower_field(self): elif rnd == "RNDU": return self._upper_field() else: return RealField(self.__prec, self.sci_not, "RNDZ") return RealField(prec=self.__prec, rnd="RNDZ", print_options=self.print_options) cdef RealIntervalFieldElement _new(self): """ from sage.categories.pushout import CompletionFunctor return (CompletionFunctor(sage.rings.infinity.Infinity, self.prec(), {'sci_not': self.scientific_notation(), 'type': 'Interval'}), {'print_options': self.print_options, 'type': 'Interval'}), sage.rings.rational_field.QQ) cdef _coerce_c_impl(self, x): False sage: RealIntervalField(10) == RealIntervalField(10) True sage: RealIntervalField(10,sci_not=True) == RealIntervalField(10,sci_not=False) sage: RealIntervalField(10,scientific_notation=True) == RealIntervalField(10,scientific_notation=False) True sage: RealIntervalField(10) == IntegerRing() False """ EXAMPLES:: sage: R = RealIntervalField(sci_not=1, prec=200) sage: R = RealIntervalField(scientific_notation=1, prec=200) sage: loads(dumps(R)) == R True """ return __create__RealIntervalField_version0, (self.__prec, self.sci_not) return __create__RealIntervalField_version1, (self.__prec, self.print_options) def random_element(self, *args): """ -  status - (bool -) optional flag """ from sage.misc.misc import deprecation if status is None: return self.sci_not else: self.sci_not = status deprecation("scientific_notation() is deprecated.  Use self.print_options['scientific_notation'] instead") return self.print_options['scientific_notation'] else: deprecation("scientific_notation() is deprecated.  Use self.print_options['scientific_notation']=value instead") self.print_options['scientific_notation'] = status def zeta(self, n=2): """ sage: a = RIF(5,5.5) sage: cmp(loads(dumps(a)), a) 0 sage: R = RealIntervalField(sci_not=1, prec=200) sage: R = RealIntervalField(scientific_notation=1, prec=200) sage: b = R('393.39203845902384098234098230948209384028340') sage: cmp(loads(dumps(b)), b) 0 """ return self._parent # MPFR had an elaborate "truncation" scheme to avoid printing # inaccurate-looking results; this has been removed for MPFI, # RealField had an elaborate "truncation" scheme to avoid printing # inaccurate-looking results; this has been removed for RealIntervalField, # because I think it's less confusing to get such results than to # see [0.333 .. 0.333] for an interval with unequal left and right # sides. def str(self, int base=10, style=None, no_sci=None, e=None, error_digits=None): def str(self, int base=10, style=None, no_sci=None, e=None, error_digits=None,scientific_notation=None): r""" INPUT: '[2.1851851851851851 .. 2.1851851851851856]' sage: a.str(16) '2.2f684bda12f69?' sage: a.str(no_sci=False) sage: a.str(scientific_notation='always') '2.185185185185186?e0' sage: pi_appr = RIF(pi, 22/7) sage: pi_appr.str(style='brackets') else: return "[.. NaN ..]" if no_sci is not None: from sage.misc.misc import deprecation deprecated_option = {True: 'extreme', False: 'always'} deprecation("The no_sci keyword is deprecated.  Use scientific_notation=%r instead."%deprecated_option[no_sci]) scientific_notation=deprecated_option[no_sci] if scientific_notation not in [None, 'always','extreme']: raise ValueError, "scientific_notation must be one of 'always', 'extreme', or 'never'." elif scientific_notation is None: scientific_notation = (self._parent).print_options.get('scientific_notation',_PRINT_OPTIONS['scientific_notation']) if e is None: if base > 10: e = '@' style = 'brackets' if style == 'brackets': t1 = self.lower().str(base=base, no_sci=no_sci, e=e, truncate=False) t2 = self.upper().str(base=base, no_sci=no_sci, e=e, truncate=False) t1 = self.lower().str(base=base, scientific_notation=scientific_notation, e=e, truncate=False) t2 = self.upper().str(base=base, scientific_notation=scientific_notation, e=e, truncate=False) return "[%s .. %s]"%(t1, t2) elif style == 'question': if no_sci == False: if scientific_notation=='always': prefer_sci = True else: elif scientific_notation=='extreme': prefer_sci = False else: raise ValueError, "scientific_notation must be 'always' or 'extreme'" return self._str_question_style(base, error_digits, e, prefer_sci) else: #### pickle functions def __create__RealIntervalField_version1(prec, print_options): return RealIntervalField(prec=prec, print_options=print_options) def __create__RealIntervalField_version0(prec, sci_not): return RealIntervalField(prec, sci_not) print_options={'scientific_notation': sci_not} return RealIntervalField(prec=prec, print_options=print_options) ## Keep all old versions!!! def __create__RealIntervalFieldElement_version0(parent, x, base=10):
• ## sage/rings/real_mpfr.pxd

diff -r 21f187597161 -r 5a0fc65a6103 sage/rings/real_mpfr.pxd
 a cdef class RealField_class(sage.rings.ring.Field): cdef int __prec cdef bint sci_not cdef object print_options cdef mpfr_rnd_t rnd cdef object rnd_str cdef RealNumber _new(self)
• ## sage/rings/real_mpfr.pyx

diff -r 21f187597161 -r 5a0fc65a6103 sage/rings/real_mpfr.pyx
 a - Robert Bradshaw (2009-09): decimal literals, optimizations - Jason Grout (2010-01): unified printing option defaults This is a binding for the MPFR arbitrary-precision floating point library. _rounding_modes = ['RNDN', 'RNDZ', 'RNDU', 'RNDD'] _PRINT_OPTIONS = {'skip_zeroes': False, 'truncate': True, 'scientific_notation': 'extreme'} # Remove sci_not_deprecation when removing the sci_not deprecation warnings sci_not_deprecation = {0: 'extreme', False: 'extreme', 1: 'always', True: 'always'} cdef object RealField_cache = weakref.WeakValueDictionary() def RealField(int prec=53, int sci_not=0, rnd="RNDN"): """ RealField(prec, sci_not, rnd): def RealField(int prec=53, scientific_notation=None, rnd="RNDN", truncate=None,skip_zeroes=None, print_options=None, sci_not=None): """ RealField(prec, scientific_notation, rnd): INPUT: implementation, 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 - scientific_notation - 'never' - never print using scientific notation; - 'extreme' (default) - print using scientific notation only for very large or very small numbers; - 'always' - always print with scientific notation; -  rnd - (string) the rounding mode - RNDU - round towards plus infinity - sci_not - deprecated.  See scientific_notation. EXAMPLES:: sage: RealField(10) numbers (double type in C), except the default exponent range is much wider and subnormal numbers are not implemented.' """ printing=_PRINT_OPTIONS.copy() if print_options is not None: printing.update(print_options) if sci_not is not None: from sage.misc.misc import deprecation deprecation("The sci_not keyword is deprecated.  Use scientific_notation=%r instead."%sci_not_deprecation[sci_not], 'Sage 4.3.2') scientific_notation=sci_not_deprecation[sci_not] if scientific_notation is not None: if scientific_notation not in ['always', 'extreme', 'never']: raise ValueError, "scientific_notation must be one of 'always', 'extreme', or 'never' (was %r)"%scientific_notation printing['scientific_notation']=scientific_notation if truncate is not None: printing['truncate']=truncate if skip_zeroes is not None: printing['skip_zeroes']=skip_zeroes print_cached=tuple(sorted(printing.items())) try: return RealField_cache[prec, sci_not, rnd] return RealField_cache[prec, rnd, print_cached] except KeyError: RealField_cache[prec, sci_not, rnd] = R = RealField_class(prec=prec, sci_not=sci_not, rnd=rnd) RealField_cache[prec, rnd, print_cached] = R = RealField_class(prec=prec, rnd=rnd, print_options=printing) return R cdef class RealField_class(sage.rings.ring.Field): details. """ def __init__(self, int prec=53, int sci_not=0, rnd="RNDN"): def __init__(self, int prec=53, scientific_notation=None, rnd="RNDN", print_options=None, sci_not=None): if sci_not is not None: from sage.misc.misc import deprecation deprecation("The sci_not keyword is deprecated.  Use print_options={'scientific_notation': %r} instead."%sci_not_deprecation[sci_not], 'Sage 4.3.1') scientific_notation=sci_not_deprecation[sci_not] global MY_MPFR_PREC_MAX if print_options is None: print_options={} if 'scientific_notation' in print_options: if scientific_notation is None: scientific_notation = print_options['scientific_notation'] else: print_options['scientific_notation']=scientific_notation else: if scientific_notation is not None: print_options['scientific_notation']=scientific_notation cdef RealNumber rn if prec < MPFR_PREC_MIN or prec > MY_MPFR_PREC_MAX: raise ValueError, "prec (=%s) must be >= %s and <= %s."%( self.__prec = prec if not isinstance(rnd, str): raise TypeError, "rnd must be a string" self.sci_not = sci_not self.print_options=print_options n = _rounding_modes.index(rnd) if n == -1: raise ValueError, "rnd (=%s) must be one of RNDN, RNDZ, RNDU, or RNDD"%rnd return s def _latex_(self): return "\\Bold{R}" """ The latex representation of self. EXAMPLE:: sage: RealField(100)._latex_() '\\Bold{R}^{}_{100}' sage: RealField(100,rnd='RNDD')._latex_() '\\Bold{R}^{-}_{100}' sage: RealField(100,rnd='RNDU')._latex_() '\\Bold{R}^{+}_{100}' sage: RealField(100,rnd='RNDZ')._latex_() '\\Bold{R}^{0}_{100}' sage: RR._latex_() '\\Bold{R}^{}_{53}' """ rnd_str={'RNDN':'', 'RNDZ':'0', 'RNDU':'+', 'RNDD':'-'} return "\\Bold{R}^{%s}_{%s}"%(rnd_str[self.rnd_str],self.__prec) def _sage_input_(self, sib, coerce): r""" return v cpdef bint is_exact(self) except -2: """ Return False, since a real field (representing using finite precision) is not exact. EXAMPLE:: sage: RR.is_exact() False sage: RealField(100).is_exact() False """ return False def _element_constructor_(self, x, base=10): """ 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 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. def __cmp__(self, other): """ Compare two real fields, returning True if they are equivalent and False if they are not. EXAMPLES:: sage: RealField(10) == RealField(11) :: sage: RealField(10,sci_not=True) == RealField(10,sci_not=False) sage: RealField(10,scientific_notation='always') == RealField(10,scientific_notation='extreme') True sage: RealField(10) == IntegerRing() False :: sage: RS = RealField(sci_not=True) sage: RS = RealField(scientific_notation='always') sage: RR == RS True sage: RS.scientific_notation(False) sage: RS.print_options['scientific_notation']='extreme' sage: RR == RS True """ cdef RealField_class _other _other = other  # to access C structure if self.__prec == _other.__prec and self.rnd == _other.rnd: \ #and self.sci_not == _other.sci_not: return 0 return 1 def __reduce__(self): """ EXAMPLES:: sage: R = RealField(sci_not=1, prec=200, rnd='RNDU') Return the arguments sufficient for pickling. EXAMPLES:: sage: R = RealField(scientific_notation='always', prec=200, rnd='RNDU') sage: loads(dumps(R)) == R True """ return __create__RealField_version0, (self.__prec, self.sci_not, self.rnd_str) return __create__RealField_version1, (self.__prec, self.rnd_str, self.print_options) def construction(self): """ Returns the functorial construction of self, namely, completion of the rational numbers with respect to the prime at \infty. Returns 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). from sage.categories.pushout import CompletionFunctor return (CompletionFunctor(sage.rings.infinity.Infinity, self.prec(), {'sci_not': self.scientific_notation(), 'rnd': self.rounding_mode()}), {'rnd': self.rounding_mode(),'print_options': self.print_options}), sage.rings.rational_field.QQ) def gen(self, i=0): """ Return the generators 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 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 """ import sage.rings.complex_field return sage.rings.complex_field.ComplexField(self.prec()) def algebraic_closure(self): """ Returns the algebraic closure of self, ie the complex field with Returns 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. EXAMPLE:: sage: RR.gens() [1.00000000000000] """ 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: 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 0 def name(self): """ Returns 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')) 5446556154562330496 # 64-bit 703053696           # 32-bit sage: hash(RR) -688242835116843476 # 64-bit -1247338964         # 32-bit """ return hash(self.name()) def precision(self): """ Returns the precision of self. EXAMPLES:: sage: RR.precision() 53 sage: RealField(20).precision() 20 """ return self.__prec def prec(self): return self.__prec prec=precision # an alias def _magma_init_(self, magma): r""" Return a string representation of self in the Magma language. .. warning:: This ignores the rounding convention of self. EXAMPLES:: def to_prec(self, prec): """ Returns the real field that is identical to self, except at the specified precision. Returns the real field that is identical to self, except that it has the specified precision. EXAMPLES:: if prec == self.__prec: return self else: return RealField(prec, self.sci_not, _rounding_modes[self.rnd]) return RealField(prec, rnd=_rounding_modes[self.rnd], print_options=self.print_options) # int mpfr_const_pi (mpfr_t rop, mp_rnd_t rnd) def pi(self): # int mpfr_const_log2 (mpfr_t rop, mp_rnd_t rnd) def log2(self): """ Returns log(2) to the precision of this field. Returns log(2) (i.e., the natural log of 2) to the precision of this field. EXAMPLES:: Returns a uniformly distributed random number between min and max (default -1 to 1). .. warning:: distribution is ignored---the random number is from the uniform distribution. EXAMPLES:: sage: RealField(100).random_element(-5, 10) def factorial(self, int n): """ Return the factorial of the integer n as a real number. Return the factorial of the integer n as a real number. EXAMPLES:: sage: RR.factorial(0) 1.00000000000000 sage: RR.factorial(1000000) 8.26393168833124e5565708 sage: RR.factorial(-1) Traceback (most recent call last): ... ArithmeticError: n must be nonnegative """ cdef RealNumber x if n < 0: return x def rounding_mode(self): """ Return the rounding mode. EXAMPLES:: sage: RR.rounding_mode() 'RNDN' sage: RealField(20,rnd='RNDZ').rounding_mode() 'RNDZ' sage: RealField(20,rnd='RNDU').rounding_mode() 'RNDU' sage: RealField(20,rnd='RNDD').rounding_mode() 'RNDD' """ return _rounding_modes[self.rnd] def scientific_notation(self, status=None): """ .. warning:: Deprecated.  See :meth:printing_options for this functionality. Set or return the scientific notation printing flag. If this flag is True then real numbers with this space as parent print using scientific notation. INPUT: -  status - (bool -) optional flag """ EXAMPLES:: sage: RR.scientific_notation() doctest:1172: DeprecationWarning: (Since Sage 4.3.1) scientific_notation() is deprecated.  Use self.print_options['scientific_notation'] True """ from sage.misc.misc import deprecation if status is None: return self.sci_not else: self.sci_not = status deprecation("scientific_notation() is deprecated.  Use self.print_options['scientific_notation']", 'Sage 4.3.1') return self.print_options.get('scientific_notation',_PRINT_OPTIONS['scientific_notation'])!='always' else: deprecation("scientific_notation() is deprecated.  Use self.print_options['scientific_notation']=value instead", 'Sage 4.3.1') if status is True: self.print_options['scientific_notation'] = 'always' else: self.print_options['scientific_notation'] = 'extreme' property print_options: """ Options for printing a real number. """ def __get__(self): """ Get the printing options. """ return self.print_options def __set__(self,newval): """ Set the printing options. """ self.print_options=newval def __del__(self): """ Reset the printing options to be empty. """ self.print_options={} def zeta(self, n=2): """ Return an n-th root of unity in the real field, if one """ EXAMPLES:: sage: R = RealField(sci_not=1, prec=200, rnd='RNDU') sage: R = RealField(scientific_notation='always', prec=200, rnd='RNDU') sage: b = R('393.39203845902384098234098230948209384028340') sage: loads(dumps(b)) == b True sage: loads(dumps(b)) == b True """ s = self.str(32, no_sci=False, e='@') s = self.str(32, scientific_notation='always', e='@') return (__create__RealNumber_version0, (self._parent, s, 32)) def  __dealloc__(self): sage: s1 == RR(gp(s1)) True """ return self.str(10, no_sci=True, truncate=False) return self.str(10, scientific_notation='extreme', truncate=False) def _sage_input_(self, sib, coerced): r""" """ return self._parent def str(self, int base=10, no_sci=None, e=None, int truncate=1, bint skip_zeroes=0): def str(self, int base=10, no_sci=None, e=None, truncate=None, skip_zeroes=None,scientific_notation=None): """ INPUT: -  base - base for output -  no_sci - if 2, never print using scientific notation; if 1 or True, print using scientific notation only for very large or very small numbers; if 0 or False always print with scientific notation; if None (the default), print how the parent prints. - scientific_notation - (default: None) - 'never' - never print using scientific notation; - 'extreme' - print using scientific notation only for very large or very small numbers; - 'always' - always print with scientific notation; - None (default) - print how the parent prints. -  e - symbol used in scientific notation; defaults to 'e' for base=10, and '@' otherwise '20.333333333333332' sage: a.str(2) '10100.010101010101010101010101010101010101010101010101' sage: a.str(no_sci=False) sage: a.str(scientific_notation='always') '2.03333333333333e1' sage: a.str(16, no_sci=False) sage: a.str(16, scientific_notation='always') '1.4555555555555@1' sage: b = 2.0^99 sage: b.str() '6.33825300114115e29' sage: b.str(no_sci=False) sage: b.str(scientific_notation='always') '6.33825300114115e29' sage: b.str(no_sci=True) sage: b.str(scientific_notation='extreme') '6.33825300114115e29' sage: c = 2.0^100 sage: c.str() '1.26765060022823e30' sage: c.str(no_sci=False) sage: c.str(scientific_notation='always') '1.26765060022823e30' sage: c.str(no_sci=True) sage: c.str(scientific_notation='extreme') '1.26765060022823e30' sage: c.str(no_sci=2) sage: c.str(scientific_notation='never') '1267650600228230000000000000000.' sage: 0.5^53 1.11022302462516e-16 """ if base < 2 or base > 36: raise ValueError, "the base (=%s) must be between 2 and 36"%base if no_sci is not None: from sage.misc.misc import deprecation deprecated_option = {0: 'always', 1: 'extreme', 2: 'never'} deprecation("The no_sci keyword is deprecated.  Use scientific_notation=%r instead."%deprecated_option[no_sci]) scientific_notation=deprecated_option[no_sci] if scientific_notation not in [None, 'always','extreme','never']: raise ValueError, "scientific_notation must be one of 'always', 'extreme', or 'never'." if mpfr_nan_p(self.value): if base >= 24: return "@NaN@" else: e = 'e' if skip_zeroes is None: skip_zeroes = (self._parent).print_options.get('skip_zeroes',_PRINT_OPTIONS['skip_zeroes']) if truncate is None: truncate = (self._parent).print_options.get('truncate',_PRINT_OPTIONS['truncate']) cdef char *s cdef mp_exp_t exponent if t[0] == "-": digits = digits - 1 if no_sci is None: no_sci = not (self._parent).sci_not if no_sci is True and ( abs(exponent-1) >=6 ): no_sci = False if no_sci==False: if scientific_notation is None: scientific_notation = (self._parent).print_options.get('scientific_notation',_PRINT_OPTIONS['scientific_notation']) if (scientific_notation=='extreme' and ( abs(exponent-1) >=6 )) \ or scientific_notation=='always': if t[0] == "-": return "-%s.%s%s%s"%(t[1:2], t[2:], e, exponent-1) return "%s.%s%s%s"%(t[0], t[1:], e, exponent-1) return x cpdef ModuleElement _neg_(self): """ Return the negative of self. EXAMPLES:: sage: RR(1)._neg_() -1.00000000000000 sage: RR('inf')._neg_() -infinity sage: RR('nan')._neg_() NaN """ cdef RealNumber x x = self._new() mpfr_neg(x.value, self.value, (self._parent).rnd) return x def __abs__(self): """ Return absolute value of self. EXAMPLES:: sage: RR(-1).__abs__() 1.00000000000000 sage: RR('-inf').__abs__() +infinity sage: RR('inf').__abs__() +infinity sage: RR('nan').__abs__() NaN """ return self.abs() cdef RealNumber abs(RealNumber self): """ Return the absolute value of self. EXAMPLES:: sage: RR('-1').abs() 1.00000000000000 sage: RR('-inf').abs() +infinity sage: RR('inf').abs() +infinity sage: RR('nan').abs() NaN """ cdef RealNumber x x = self._new() mpfr_abs(x.value, self.value, (self._parent).rnd) # Bit shifting def _lshift_(RealNumber self, n): """ Return self*(2^n) for an integer n. EXAMPLES:: sage: RR(1.0)._lshift_(32) 4.29496729600000e9 sage: RR(1.5)._lshift_(2) 6.00000000000000 """ cdef RealNumber x if n > sys.maxint: raise OverflowError, "n (=%s) must be <= %s"%(n, sys.maxint) x = self._new() mpfr_mul_2exp(x.value, self.value, n, (self._parent).rnd) mpfr_mul_2ui(x.value, self.value, n, (self._parent).rnd) return x def __lshift__(x, y): """ Return self*(2^n) for an integer n. EXAMPLES:: sage: 1.0 << 32 raise TypeError, "unsupported operands for <<" def _rshift_(RealNumber self, n): """ Return self/(2^n) for an integer n. EXAMPLES:: sage: RR(1.0)._rshift_(32) 2.32830643653870e-10 sage: RR(1.5)._rshift_(2) 0.375000000000000 """ if n > sys.maxint: raise OverflowError, "n (=%s) must be <= %s"%(n, sys.maxint) cdef RealNumber x def __rshift__(x, y): """ Return self/(2^n) for an integer n. EXAMPLES:: sage: 1024.0 >> 7 """ return mpfr_sgn(self.value) def prec(self): def precision(self): """ Return the precision of self. EXAMPLES:: sage: RR(1.0).precision() 53 sage: RealField(101)(-1).precision() 101 """ return (self._parent).__prec prec = precision # alias def conjugate(self): """ Return the complex conjugate of this real number, which is the mpfr_ceil(x.value, self.value) return x.integer_part() def ceiling(self): return self.ceil() ceiling = ceil # alias def trunc(self): """ def frac(self): """ frac returns a real number > -1 and < 1. it satisfies the relation: x = x.trunc() + x.frac() Returns a real number such that self = self.trunc() + self.frac().  The return value will also satisfy -1 < self.frac() < 1. EXAMPLES:: 0.500000000000000 sage: (-2.79).frac() -0.790000000000000 sage: (-2.79).trunc() + (-2.79).frac() -2.79000000000000 """ cdef RealNumber x x = self._new() ########################################### def __float__(self): """ Returns a python float approximating self. EXAMPLES:: sage: RR(pi).__float__() 3.1415926535897931 sage: type(RR(pi).__float__()) """ return mpfr_get_d(self.value, (self._parent).rnd) def _rpy_(self): def __int__(self): """ Returns integer truncation of this real number. Returns the python integer truncation of self. EXAMPLES:: sage: RR(pi).__int__() 3 sage: type(RR(pi).__int__()) """ if not mpfr_number_p(self.value): raise ValueError, 'Cannot convert infinity or NaN to Python int' def __long__(self): """ Returns long integer truncation of this real number. Returns python long integer truncation of this real number. EXAMPLES:: sage: RR(pi).__long__() 3L sage: type(RR(pi).__long__()) """ if not mpfr_number_p(self.value): raise ValueError, 'Cannot convert infinity or NaN to Python long' return z.__long__() def __complex__(self): """ Returns a python complex number equal to self. EXAMPLES:: sage: RR(pi).__complex__() (3.1415926535897931+0j) sage: type(RR(pi).__complex__()) """ return complex(float(self)) def _complex_number_(self): """ Returns a Sage complex number equal to self. EXAMPLES:: sage: RR(pi)._complex_number_() 3.14159265358979 sage: parent(RR(pi)._complex_number_()) Complex Field with 53 bits of precision """ import sage.rings.complex_field return sage.rings.complex_field.ComplexField(self.prec())(self) def is_infinity(self): """ Return True if self is infinite and False otherwise. EXAMPLES:: sage: a = RR('1.494') / RR(0); a True sage: RR(1.5).is_infinity() False sage: RR('nan').is_infinity() False """ return mpfr_inf_p(self.value) def is_unit(self): """ Return True if self is a unit (has a multiplicative inverse) and False otherwise. EXAMPLES:: sage: RR(1).is_unit() True sage: RR('0').is_unit() False sage: RR('-0').is_unit() False sage: RR('nan').is_unit() False sage: RR('inf').is_unit() False sage: RR('-inf').is_unit() False """ return mpfr_sgn(self.value) != 0 and not mpfr_inf_p(self.value) def is_real(self): """ Return True if self is real (of course, this always returns True for a finite element of a real field). EXAMPLES:: sage: RR(1).is_real() True sage: RR('-100').is_real() True """ return True def __nonzero__(self): """ Returns True if self is nonzero. EXAMPLES:: sage: RR(1).__nonzero__() True sage: RR(0).__nonzero__() False sage: RR('inf').__nonzero__() True """ return mpfr_sgn(self.value) != 0 def is_real(self): return True def __nonzero__(self): return mpfr_sgn(self.value) != 0 def __richcmp__(left, right, int op): """ Return the cython rich comparison operator (see the cython documentation for details). EXAMPLES:: sage: RR('-inf')RR('inf') False sage: RR('100000000')RR('1') False sage: RR('1')>=RR('1') True """ return (left)._richcmp(right, op) cdef int _cmp_c_impl(left, Element right) except -2: """ Returns -1 if exactly one of the numbers is NaN.  Return -1 if left is less than right, 0 if left and right are equal, and 1 if left is greater than right. EXAMPLES:: sage: RR('1')<=RR('1') True sage: RR('1')RR('1') False sage: RR('1')>=RR('1') True sage: RR('nan')==R('nan') False sage: RR('inf')==RR('inf') True sage: RR('inf')==RR('-inf') False """ cdef RealNumber self, x self = left x = right return x def __pow(self, RealNumber exponent): """ Compute self raised to the power of exponent, rounded in the direction specified by the parent of self. EXAMPLES:: sage: R = RealField(30) sage: a = R('1.23456') sage: a.__pow(20.0) 67.646297 """ cdef RealNumber x x = self._new() _sig_on def log1p(self): """ Returns log of 1 + self Returns log base e of 1 + self EXAMPLES:: # here because this imports the other two real fields def create_RealField(prec=53, type="MPFR", rnd="RNDN", sci_not=0): def create_RealField(prec=53, type="MPFR", rnd="RNDN", scientific_notation=None, print_options={},sci_not=None): """ A generic constructor that returns the appropriate real field. INPUTS: - type - MPFR - A real field with precision prec and the specified printing options. - RDF - A real field with double precision - RQDF - A real field with quad double precision - RLF - A real lazy field - Interval - A real interval field with prec precision and the specified printing options """ if type == "RDF": return RDF elif type == "RQDF": return RQDF elif type == "Interval": from real_mpfi import RealIntervalField return RealIntervalField(prec, sci_not) return RealIntervalField(prec=prec, scientific_notation=scientific_notation, print_options=print_options, sci_not=sci_not) elif type == "RLF": from real_lazy import RLF return RLF else: return RealField(prec, sci_not, rnd) return RealField(prec=prec, scientific_notation=scientific_notation, rnd=rnd, print_options=print_options, sci_not=sci_not) def is_RealField(x): """ Returns True if x is technically of a python real field type. EXAMPLES:: sage: sage.rings.real_mpfr.is_RealField(RR) True sage: sage.rings.real_mpfr.is_RealField(CC) False """ return PY_TYPE_CHECK(x, RealField_class) def is_RealNumber(x): """ return PY_TYPE_CHECK(x, RealNumber) def __create__RealField_version1(prec, rnd, print_options): """ Return a real field with precision prec, rounding rnd, and print options print_options. EXAMPLES:: sage: sage.rings.real_mpfr.__create__RealField_version1(50, 'RNDD',{}) Real Field with 50 bits of precision and rounding RNDD """ return RealField(prec=prec, rnd=rnd, print_options=print_options) def __create__RealField_version0(prec, sci_not, rnd): return RealField(prec, sci_not, rnd) """ Return a real field with precision prec, rounding rnd, and the specified scientific notation setting. EXAMPLES:: sage: sage.rings.real_mpfr.__create__RealField_version1(50, 'RNDD',{}) Real Field with 50 bits of precision and rounding RNDD sage: R=sage.rings.real_mpfr.__create__RealField_version0(50, True, 'RNDD') sage: R.print_options {'scientific_notation': 'always', 'skip_zeroes': False, 'truncate': True} """ print_options={'scientific_notation':sci_not_deprecation[sci_not]} return RealField(prec=prec, rnd=rnd, print_options=print_options) def __create__RealNumber_version0(parent, x, base=10): """ Create a real number. EXAMPLES:: sage: sage.rings.real_mpfr.__create__RealNumber_version0(RR, 22,base=3) 22.0000000000000 """ return RealNumber(parent, x, base=base) cdef inline RealNumber empty_RealNumber(RealField_class parent): """ Create and return an empty initialized real number. EXAMPLES: These are indirect tests of this function. sage: from sage.rings.real_mpfr import RRtoRR sage: R10 = RealField(10) sage: R100 = RealField(100) sage: f = RRtoRR(R100, R10) sage: a = R100(1.2) sage: f(a) 1.2 sage: g = f.section() sage: g Generic map: From: Real Field with 10 bits of precision To:   Real Field with 100 bits of precision sage: g(f(a)) 1.1992187500000000000000000000 sage: b = R10(2).sqrt() sage: f(g(b)) 1.4 sage: f(g(b)) == b True """ cdef RealNumber y = PY_NEW(RealNumber) y._parent = parent mpfr_init2(y.value, parent.__prec)