26.3 Field of Arbitrary Precision Real Numbers

Module: sage.rings.real_mpfr

Field of Arbitrary Precision Real Numbers

Author Log:

This is a binding for the MPFR arbitrary-precision floating point library.

We define a class RealField, where each instance of 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^{30} + 1 \leq e \leq 2^{30} - 1$ ; plus 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 nunbers, 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.)

A difficult conversion:

sage: RR(sys.maxint)
9.22337203685478e18      # 64-bit
2.14748364700000e9       # 32-bit

TESTS:

sage: -1e30
-1.00000000000000e30

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

Module-level Functions

RealField_constructor( )

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 mpfr_prec_min() and mpfr_prec_max(). In the current 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

rnd - (string) the rounding mode RNDN - (default) round to nearest: 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

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

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.'

create_RealField( )

create_RealNumber( )

Return the real number defined by the string s as an element of RealField(prec=n), where n potentially has slightly more (controlled by pad) bits than given by s.

Input:

s
- a string that defines a real number (or something whose string representation defines a number)
base
- an integer between 2 and 36
pad
- an integer >= 0.
rnd
- rounding mode: RNDN, RNDZ, RNDU, RNDD
min_prec
- number will have at least this many bits of precision, no matter what.

sage: RealNumber('2.3')
2.30000000000000
sage: RealNumber(10)
10.0000000000000
sage: RealNumber('1.0000000000000000000000000000000000')
1.0000000000000000000000000000000000

is_RealField( )

is_RealNumber( )

Return True if x is of type RealNumber, meaning that it is an element of the MPFR real field with some precision.

sage: is_RealNumber(2.5)
True
sage: is_RealNumber(float(2.3))
False
sage: is_RealNumber(RDF(2))
False
sage: is_RealNumber(pi)
False

mpfr_prec_max( )

mpfr_prec_min( )

Return the mpfr variable MPFR_PREC_MIN.

Class: RealField

class RealField
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 sage.rings.real_mpfr for more details.

Functions: algebraic_closure,$ \,$ catalan_constant,$ \,$ characteristic,$ \,$ complex_field,$ \,$ construction,$ \,$ euler_constant,$ \,$ factorial,$ \,$ gen,$ \,$ gens,$ \,$ is_atomic_repr,$ \,$ is_exact,$ \,$ is_finite,$ \,$ log2,$ \,$ name,$ \,$ ngens,$ \,$ pi,$ \,$ prec,$ \,$ precision,$ \,$ random_element,$ \,$ rounding_mode,$ \,$ scientific_notation,$ \,$ zeta

algebraic_closure( )

Returns the algebraic closure of self, ie the complex field with the same precision.

catalan_constant( )

Returns Catalan's constant to the precision of this field.

sage: RealField(100).catalan_constant()
0.91596559417721901505460351493

characteristic( )

Returns 0, since the field of real numbers has characteristic 0.

sage: RealField(10).characteristic()
0

complex_field( )

Return complex field of the same precision.

construction( )

Returns the functorial construction of self, namely, completion of the rational numbers with respect to the prime at $ \infinity$ .

Also preserves other information that makes this field unique (e.g. precision, rounding, print mode).

sage: R = RealField(100, rnd='RNDU')
sage: c, S = R.construction(); S
Rational Field
sage: R == c(S)
True

euler_constant( )

Returns Euler's gamma constant to the precision of this field.

sage: RealField(100).euler_constant()
0.57721566490153286060651209008

factorial( )

Return the factorial of the integer n as a real number.

is_atomic_repr( )

Returns True, to signify that elements of this field print without sums, so parenthesis aren't required, e.g., in coefficients of polynomials.

sage: RealField(10).is_atomic_repr()
True

is_finite( )

Returns False, since the field of real numbers is not finite.

sage: RealField(10).is_finite()
False

log2( )

Returns log(2) to the precision of this field.

sage: R=RealField(100)
sage: R.log2() 
0.69314718055994530941723212146
sage: R(2).log()
0.69314718055994530941723212146

pi( )

Returns pi to the precision of this field.

sage: R = RealField(100)
sage: R.pi()
3.1415926535897932384626433833
sage: R.pi().sqrt()/2
0.88622692545275801364908374167
sage: R = RealField(150)
sage: R.pi().sqrt()/2
0.88622692545275801364908374167057259139877473

random_element( )

Returns a uniformly distributed random number between min and max (default -1 to 1).

sage: RealField(100).random_element(-5, 10)
1.9305310520925994224072377281
sage: RealField(10).random_element()
-0.84

TESTS:

sage: RealField(31).random_element()
-0.207006278
sage: RealField(32).random_element()
-0.757827933
sage: RealField(33).random_element()
-0.530834221
sage: RealField(63).random_element()
0.918013195263849341
sage: RealField(64).random_element()
-0.805114150788947694
sage: RealField(65).random_element()
0.2035927570696802284
sage: RealField(10).random_element()
-0.59
sage: RealField(10).random_element()
0.57
sage: RR.random_element()
0.931242676441124
sage: RR.random_element()
0.979095507956490

scientific_notation( )

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

zeta( )

Return an $ n$ -th root of unity in the real field, if one exists, or raise a ValueError otherwise.

sage: R = RealField()
sage: R.zeta()
-1.00000000000000
sage: R.zeta(1)
1.00000000000000
sage: R.zeta(5)
Traceback (most recent call last):
...
ValueError: No 5th root of unity in self

Special Functions: __call__,$ \,$ __cmp__,$ \,$ __init__,$ \,$ __reduce__,$ \,$ _is_valid_homomorphism_,$ \,$ _latex_,$ \,$ _repr_

__call__( )

Coerce x into this real field.

sage: R = RealField(20)
sage: R('1.234')
1.2340
sage: R('2', base=2)
Traceback (most recent call last):
...
TypeError: Unable to convert x (='2') to real number.
sage: a = R('1.1001', base=2); a
1.5625
sage: a.str(2)
'1.1001000000000000000'
sage: w = RQDF('2.345001').sqrt(); w
1.531339609622894852128128425884749978483262262653204338472911277
sage: RealField(212)(w)
1.53133960962289485212812842588474997848326226265320433847291128
sage: RR(w)
1.53133960962289

__reduce__( )

sage: R = RealField(sci_not=1, prec=200, rnd='RNDU')
sage: loads(dumps(R)) == R
True

_is_valid_homomorphism_( )

_latex_( )

_repr_( )

Class: RealNumber

class RealNumber
A floating point approximation to a real number using any specified precision. Answers derived from calculations with such approximations may differ from what they would be if those calculations were performed with true real numbers. This is due to the rounding errors inherent to finite precision calculations.

The approximation is printed to slightly fewer digits than its internal precision, in order to avoid confusing roundoff issues that occur because numbers are stored internally in binary.

Functions: agm,$ \,$ algdep,$ \,$ algebraic_dependency,$ \,$ arccos,$ \,$ arccosh,$ \,$ arcsin,$ \,$ arcsinh,$ \,$ arctan,$ \,$ arctanh,$ \,$ ceil,$ \,$ ceiling,$ \,$ cos,$ \,$ cosh,$ \,$ cot,$ \,$ coth,$ \,$ csc,$ \,$ csch,$ \,$ cube_root,$ \,$ eint,$ \,$ erf,$ \,$ erfc,$ \,$ exact_rational,$ \,$ exp,$ \,$ exp10,$ \,$ exp2,$ \,$ expm1,$ \,$ floor,$ \,$ fp_rank,$ \,$ fp_rank_delta,$ \,$ frac,$ \,$ gamma,$ \,$ integer_part,$ \,$ is_infinity,$ \,$ is_NaN,$ \,$ is_negative_infinity,$ \,$ is_positive_infinity,$ \,$ is_square,$ \,$ is_unit,$ \,$ j0,$ \,$ j1,$ \,$ jn,$ \,$ lngamma,$ \,$ log,$ \,$ log10,$ \,$ log1p,$ \,$ log2,$ \,$ multiplicative_order,$ \,$ nearby_rational,$ \,$ nextabove,$ \,$ nextbelow,$ \,$ nexttoward,$ \,$ nth_root,$ \,$ parent,$ \,$ prec,$ \,$ real,$ \,$ round,$ \,$ sec,$ \,$ sech,$ \,$ sign,$ \,$ simplest_rational,$ \,$ sin,$ \,$ sincos,$ \,$ sinh,$ \,$ sqrt,$ \,$ str,$ \,$ tan,$ \,$ tanh,$ \,$ trunc,$ \,$ y0,$ \,$ y1,$ \,$ yn,$ \,$ zeta

agm( )

Return the arithmetic-geometric mean of self and other. The arithmetic-geometric mean is the common limit of the sequences $ u_n$ and $ v_n$ , where $ u_0$ is self, $ v_0$ is other, $ u_{n+1}$ is the arithmetic mean of $ u_n$ and $ v_n$ , and $ v_{n+1}$ is the geometric mean of u_n and v_n. If any operand is negative, the return value is NaN.

algdep( )

Returns a polynomial of degree at most $ n$ which is approximately satisfied by this number. Note that the returned polynomial need not be irreducible, and indeed usually won't be if this number is a good approximation to an algebraic number of degree less than $ n$ .

ALGORITHM: Uses the PARI C-library algdep command.

sage: r = sqrt(2.0); r
1.41421356237310
sage: r.algdep(5)
x^2 - 2

algebraic_dependency( )

Returns a polynomial of degree at most $ n$ which is approximately satisfied by this number. Note that the returned polynomial need not be irreducible, and indeed usually won't be if this number is a good approximation to an algebraic number of degree less than $ n$ .

ALGORITHM: Uses the PARI C-library algdep command.

sage: r = sqrt(2.0); r
1.41421356237310
sage: r.algdep(5)
x^2 - 2

arccos( )

Returns the inverse cosine of this number

sage: q = RR.pi()/3
sage: i = q.cos()
sage: i.arccos() == q
True

arccosh( )

Returns the hyperbolic inverse cosine of this number

sage: q = RR.pi()/2 
sage: i = q.cosh() ; i
2.50917847865806
sage: q == i.arccosh()
True

arcsin( )

Returns the inverse sine of this number

sage: q = RR.pi()/5
sage: i = q.sin()
sage: i.arcsin() == q
True
sage: i.arcsin() - q
0.000000000000000

arcsinh( )

Returns the hyperbolic inverse sine of this number

sage: q = RR.pi()/7 
sage: i = q.sinh() ; i
0.464017630492991
sage: i.arcsinh() - q
0.000000000000000

arctan( )

Returns the inverse tangent of this number

sage: q = RR.pi()/5
sage: i = q.tan()
sage: i.arctan() == q
True

arctanh( )

Returns the hyperbolic inverse tangent of this number

sage: q = RR.pi()/7 
sage: i = q.tanh() ; i
0.420911241048535
sage: i.arctanh() - q
0.000000000000000

ceil( )

Returns the ceiling of this number

Output: integer

sage: (2.99).ceil()
3
sage: (2.00).ceil()
2
sage: (2.01).ceil()
3

sage: ceil(10^16 * 1.0)
10000000000000000
sage: ceil(10^17 * 1.0)
100000000000000000
sage: ceil(RR(+infinity))
Traceback (most recent call last):
...
ValueError: Calling ceil() on infinity or NaN

cos( )

Returns the cosine of this number

sage: t=RR.pi()/2
sage: t.cos()
6.12323399573677e-17

cosh( )

Returns the hyperbolic cosine of this number

sage: q = RR.pi()/12
sage: q.cosh()
1.03446564009551

cot( )

Returns the cotangent of this number

sage: RealField(100)(2).cot()
-0.45765755436028576375027741043

coth( )

Returns the hyperbolic cotangent of this number

sage: RealField(100)(2).coth()
1.0373147207275480958778097648

csc( )

Returns the cosecant of this number

sage: RealField(100)(2).csc()
1.0997501702946164667566973970

csch( )

Returns the hyperbolic cosecant of this number

sage: RealField(100)(2).csch()
0.27572056477178320775835148216

cube_root( )

Return the cubic root (defined over the real numbers) of self.

sage: r = 125.0; r.cube_root()
5.00000000000000
sage: r = -119.0
sage: r.cube_root()^3 - r       # illustrates precision loss
-1.42108547152020e-14

eint( )

Returns the exponential integral of this number.

sage: r = 1.0
sage: r.eint()
1.89511781635594

sage: r = -1.0
sage: r.eint()
NaN

erf( )

Returns the value of the error function on self.

sage: R = RealField(53)
sage: R(2).erf()
0.995322265018953
sage: R(6).erf()
1.00000000000000

erfc( )

Returns the value of the complementary error function on self, i.e., $ 1-\code{erf}(\code{self})$ .

sage: R = RealField(53)
sage: R(2).erfc()
0.00467773498104727
sage: R(6).erfc()
2.15197367124989e-17

exact_rational( )

Returns the exact rational representation of this floating-point number.

sage: RR(0).exact_rational()
0
sage: RR(1/3).exact_rational()
6004799503160661/18014398509481984
sage: RR(37/16).exact_rational()
37/16
sage: RR(3^60).exact_rational()
42391158275216203520420085760
sage: RR(3^60).exact_rational() - 3^60
6125652559
sage: RealField(5)(-pi).exact_rational()
-25/8

TESTS:

sage: RR('nan').exact_rational()
Traceback (most recent call last):
...
ValueError: Cannot convert NaN or infinity to rational number
sage: RR('-infinity').exact_rational()
Traceback (most recent call last):
...
ValueError: Cannot convert NaN or infinity to rational number

exp( )

Returns $ e^\code{self}$

sage: r = 0.0
sage: r.exp()
1.00000000000000

sage: r = 32.3
sage: a = r.exp(); a
1.06588847274864e14
sage: a.log()
32.3000000000000

sage: r = -32.3
sage: r.exp()
9.38184458849869e-15

exp10( )

Returns $ 10^\code{self}$

sage: r = 0.0
sage: r.exp10()
1.00000000000000

sage: r = 32.0
sage: r.exp10()
1.00000000000000e32

sage: r = -32.3
sage: r.exp10()
5.01187233627276e-33

exp2( )

Returns $ 2^\code{self}$

sage: r = 0.0
sage: r.exp2()
1.00000000000000

sage: r = 32.0
sage: r.exp2()
4.29496729600000e9

sage: r = -32.3
sage: r.exp2()
1.89117248253021e-10

expm1( )

Returns $ e^\code{self}-1$ , avoiding cancellation near 0.

sage: r = 1.0
sage: r.expm1()
1.71828182845905

sage: r = 1e-16
sage: exp(r)-1
0.000000000000000
sage: r.expm1()
1.00000000000000e-16

floor( )

Returns the floor of this number

sage: R = RealField()
sage: (2.99).floor()
2
sage: (2.00).floor()
2
sage: floor(RR(-5/2))
-3
sage: floor(RR(+infinity))
Traceback (most recent call last):
...
ValueError: Calling floor() on infinity or NaN

fp_rank( )

Returns the floating-point rank of this number. That is, if you list the floating-point numbers of this precision in order, and number them starting with 0.0 $ \rightarrow$ 0 and extending the list to positive and negative infinity, returns the number corresponding to this floating-point number.

sage: RR(0).fp_rank()
0
sage: RR(0).nextabove().fp_rank()
1
sage: RR(0).nextbelow().nextbelow().fp_rank()
-2
sage: RR(1).fp_rank()
4835703278458516698824705
sage: RR(-1).fp_rank()
-4835703278458516698824705
sage: RR(1).fp_rank() - RR(1).nextbelow().fp_rank()
1
sage: RR(-infinity).fp_rank()
-9671406552413433770278913
sage: RR(-infinity).fp_rank() - RR(-infinity).nextabove().fp_rank()
-1

fp_rank_delta( )

Return the floating-point rank delta between self and other. That is, if the return value is positive, this is the number of times you have to call .nextabove() to get from self to other.

sage: [x.fp_rank_delta(x.nextabove()) for x in
...      (RR(-infinity), -1.0, 0.0, 1.0, RR(pi), RR(infinity))]
[1, 1, 1, 1, 1, 0]

In the 2-bit floating-point field, one subsegment of the floating-point numbers is: 1, 1.5, 2, 3, 4, 6, 8, 12, 16, 24, 32

sage: R2 = RealField(2)
sage: R2(1).fp_rank_delta(R2(2))
2
sage: R2(2).fp_rank_delta(R2(1))
-2
sage: R2(1).fp_rank_delta(R2(1048576))
40
sage: R2(24).fp_rank_delta(R2(4))
-5
sage: R2(-4).fp_rank_delta(R2(-24))
-5

There are lots of floating-point numbers around 0:

sage: R2(-1).fp_rank_delta(R2(1))
4294967298

frac( )

frac returns a real number > -1 and < 1. it satisfies the relation: x = x.trunc() + x.frac()

sage: (2.99).frac()
0.990000000000000
sage: (2.50).frac()
0.500000000000000
sage: (-2.79).frac()
-0.790000000000000

gamma( )

The Euler gamma function. Return gamma of self.

sage: R = RealField()
sage: R(6).gamma()
120.000000000000
sage: R(1.5).gamma()
0.886226925452758

integer_part( )

If in decimal this number is written n.defg, returns n.

Output:

- a SAGE Integer

sage: a = 119.41212
sage: a.integer_part()
119
sage: a = -123.4567
sage: a.integer_part()
-123

A big number with no decimal point:

sage: a = RR(10^17); a
1.00000000000000e17
sage: a.integer_part()
100000000000000000

is_infinity( )

sage: a = RR('1.494') / RR(0); a
+infinity
sage: a.is_infinity()
True
sage: a = -RR('1.494') / RR(0); a
-infinity
sage: a.is_infinity()
True
sage: RR(1.5).is_infinity()
False

is_negative_infinity( )

sage: a = RR('1.494') / RR(0); a
+infinity
sage: a.is_negative_infinity()
False
sage: a = -RR('1.494') / RR(0); a
-infinity
sage: RR(1.5).is_negative_infinity()
False
sage: a.is_negative_infinity()
True

is_positive_infinity( )

sage: a = RR('1.494') / RR(0); a
+infinity
sage: a.is_positive_infinity()
True
sage: a = -RR('1.494') / RR(0); a
-infinity
sage: RR(1.5).is_positive_infinity()
False
sage: a.is_positive_infinity()
False

is_square( )

Returns whether or not this number is a square in this field. For the real numbers, this is True if and only if self is non-negative.

sage: r = 3.5
sage: r.is_square()
True
sage: r = 0.0
sage: r.is_square()
True
sage: r = -4.0
sage: r.is_square()
False

j0( )

Returns the value of the Bessel J function of order 0 at self.

sage: R = RealField(53)
sage: R(2).j0()
0.223890779141236

j1( )

Returns the value of the Bessel J function of order 1 at self.

sage: R = RealField(53)
sage: R(2).j1()
0.576724807756873

jn( )

Returns the value of the Bessel J function of order $ n$ at self.

sage: R = RealField(53)
sage: R(2).jn(3)
0.128943249474402
sage: R(2).jn(-17)
-2.65930780516787e-15

lngamma( )

Return the logarithm of gamma of self.

sage: R = RealField(53)
sage: R(6).lngamma()
4.78749174278205
sage: R(1e10).lngamma()
2.20258509288811e11

log( )

sage: R = RealField()
sage: R(2).log()
0.693147180559945

log10( )

Returns log to the base 10 of self

sage: r = 16.0; r.log10()
1.20411998265592
sage: r.log() / log(10.0)
1.20411998265592

sage: r = 39.9; r.log10()
1.60097289568675

sage: r = 0.0
sage: r.log10()
-infinity

sage: r = -1.0
sage: r.log10()
NaN

log1p( )

Returns log of 1 + self

sage: r = 15.0; r.log1p()
2.77258872223978
sage: (r+1).log()
2.77258872223978

sage: r = 38.9; r.log1p()
3.68637632389582

sage: r = -1.0
sage: r.log1p()
-infinity

sage: r = -2.0
sage: r.log1p()
NaN

log2( )

Returns log to the base 2 of self

sage: r = 16.0
sage: r.log2()
4.00000000000000

sage: r = 31.9; r.log2()
4.99548451887751

sage: r = 0.0
sage: r.log2()
-infinity

nearby_rational( )

Find a rational near to self. Exactly one of max_error or max_denominator must be specified. If max_error is specified, then this returns the simplest rational in the range [self-max_error .. self+max_error]. If max_denominator is specified, then this returns the rational closest to self with denominator at most max_denominator. (In case of ties, we pick the simpler rational.)

sage: (0.333).nearby_rational(max_error=0.001)
1/3
sage: (0.333).nearby_rational(max_error=1)
0
sage: (-0.333).nearby_rational(max_error=0.0001)
-257/772

sage: (0.333).nearby_rational(max_denominator=100)
1/3
sage: RR(1/3 + 1/1000000).nearby_rational(max_denominator=2999999)
777780/2333333
sage: RR(1/3 + 1/1000000).nearby_rational(max_denominator=3000000)
1000003/3000000
sage: (-0.333).nearby_rational(max_denominator=1000)
-333/1000
sage: RR(3/4).nearby_rational(max_denominator=2)
1
sage: RR(pi).nearby_rational(max_denominator=120)
355/113
sage: RR(pi).nearby_rational(max_denominator=10000)
355/113
sage: RR(pi).nearby_rational(max_denominator=100000)
312689/99532
sage: RR(pi).nearby_rational(max_denominator=1)
3
sage: RR(-3.5).nearby_rational(max_denominator=1)
-3

TESTS:

sage: RR('nan').nearby_rational(max_denominator=1000)
Traceback (most recent call last):
...
ValueError: Cannot convert NaN or infinity to rational number
sage: RR('nan').nearby_rational(max_error=0.01)
Traceback (most recent call last):
...
ValueError: Cannot convert NaN or infinity to rational number
sage: RR('infinity').nearby_rational(max_denominator=1000)
Traceback (most recent call last):
...
ValueError: Cannot convert NaN or infinity to rational number
sage: RR('infinity').nearby_rational(max_error=0.01)
Traceback (most recent call last):
...
ValueError: Cannot convert NaN or infinity to rational number

nextabove( )

Returns the next floating-point number larger than self.

sage: RR('-infinity').nextabove()
-2.09857871646739e323228496
sage: RR(0).nextabove()
2.38256490488795e-323228497
sage: RR('+infinity').nextabove()
+infinity
sage: RR(-sqrt(2)).str(truncate=False)
'-1.4142135623730951'
sage: RR(-sqrt(2)).nextabove().str(truncate=False)
'-1.4142135623730949'

nextbelow( )

Returns the next floating-point number smaller than self.

sage: RR('-infinity').nextbelow()
-infinity
sage: RR(0).nextbelow()
-2.38256490488795e-323228497
sage: RR('+infinity').nextbelow()
2.09857871646739e323228496
sage: RR(-sqrt(2)).str(truncate=False)
'-1.4142135623730951'
sage: RR(-sqrt(2)).nextbelow().str(truncate=False)
'-1.4142135623730954'

nexttoward( )

Returns the floating-point number adjacent to self which is closer to other. If self or other is NaN, returns NaN; if self equals other, returns self.

sage: (1.0).nexttoward(2).str(truncate=False)
'1.0000000000000002'
sage: (1.0).nexttoward(RR('-infinity')).str(truncate=False)
'0.99999999999999989'
sage: RR(infinity).nexttoward(0)
2.09857871646739e323228496
sage: RR(pi).str(truncate=False)
'3.1415926535897931'
sage: RR(pi).nexttoward(22/7).str(truncate=False)
'3.1415926535897936'
sage: RR(pi).nexttoward(21/7).str(truncate=False)
'3.1415926535897927'

nth_root( )

Returns an $ n^{th}$ root of self.

Input:

n
- A positive number, rounded down to the nearest integer. Note that $ n$ should be less than $ \code{sys.maxint}$ .
algorithm
- Set this to 1 to call mpfr directly, set this to 2 to use interval arithmetic and logarithms, or leave it at the default of 0 to choose the algorithm which is estimated to be faster.

Author: Carl Witty (2007-10)

sage: R = RealField()
sage: R(8).nth_root(3)
2.00000000000000
sage: R(8).nth_root(3.7)    # illustrate rounding down
2.00000000000000
sage: R(-8).nth_root(3)
-2.00000000000000
sage: R(0).nth_root(3)
0.000000000000000
sage: R(32).nth_root(-1)
Traceback (most recent call last):
...
ValueError: n must be positive
sage: R(32).nth_root(1.0)
32.0000000000000
sage: R(4).nth_root(4)
1.41421356237310
sage: R(4).nth_root(40)
1.03526492384138
sage: R(4).nth_root(400)
1.00347174850950
sage: R(4).nth_root(4000)
1.00034663365385
sage: R(4).nth_root(4000000)
1.00000034657365
sage: R(-27).nth_root(3)
-3.00000000000000
sage: R(-4).nth_root(3999999)
-1.00000034657374

Note that for negative numbers, any even root throws an exception

sage: R(-2).nth_root(6)
Traceback (most recent call last):
...
ValueError: taking an even root of a negative number

The $ n^{th}$ root of 0 is defined to be 0, for any $ n$

sage: R(0).nth_root(6)
0.000000000000000

sage: R(0).nth_root(7)
0.000000000000000

TESTS: The old and new algorithms should give exactly the same results in all cases.

sage: def check(x, n):
...       answers = []
...       for sign in (1, -1):
...           if is_even(n) and sign == -1:
...               continue
...           for rounding in ('RNDN', 'RNDD', 'RNDU', 'RNDZ'):
...               fld = RealField(x.prec(), rnd=rounding)
...               fx = fld(sign * x)
...               alg_mpfr = fx.nth_root(n, algorithm=1)
...               alg_mpfi = fx.nth_root(n, algorithm=2)
...               assert(alg_mpfr == alg_mpfi)
...               if sign == 1: answers.append(alg_mpfr)
...       return answers

Check some perfect powers (and nearby numbers).

sage: check(16.0, 4)
[2.00000000000000, 2.00000000000000, 2.00000000000000, 2.00000000000000]
sage: check((16.0).nextabove(), 4)
[2.00000000000000, 2.00000000000000, 2.00000000000001, 2.00000000000000]
sage: check((16.0).nextbelow(), 4)
[2.00000000000000, 1.99999999999999, 2.00000000000000, 1.99999999999999]
sage: check(((9.0 * 256)^7), 7)
[2304.00000000000, 2304.00000000000, 2304.00000000000, 2304.00000000000]
sage: check(((9.0 * 256)^7).nextabove(), 7)
[2304.00000000000, 2304.00000000000, 2304.00000000001, 2304.00000000000]
sage: check(((9.0 * 256)^7).nextbelow(), 7)
[2304.00000000000, 2303.99999999999, 2304.00000000000, 2303.99999999999]
sage: check(((5.0 / 512)^17), 17)
[0.00976562500000000, 0.00976562500000000, 0.00976562500000000,
0.00976562500000000]
sage: check(((5.0 / 512)^17).nextabove(), 17)
[0.00976562500000000, 0.00976562500000000, 0.00976562500000001,
0.00976562500000000]
sage: check(((5.0 / 512)^17).nextbelow(), 17)
[0.00976562500000000, 0.00976562499999999, 0.00976562500000000,
0.00976562499999999]

And check some non-perfect powers:

sage: check(2.0, 3)
[1.25992104989487, 1.25992104989487, 1.25992104989488, 1.25992104989487]
sage: check(2.0, 4)
[1.18920711500272, 1.18920711500272, 1.18920711500273, 1.18920711500272]
sage: check(2.0, 5)
[1.14869835499704, 1.14869835499703, 1.14869835499704, 1.14869835499703]

And some different precisions:

sage: check(RealField(20)(22/7), 19)
[1.0621, 1.0621, 1.0622, 1.0621]
sage: check(RealField(200)(e), 4)
[1.2840254166877414840734205680624364583362808652814630892175,
1.2840254166877414840734205680624364583362808652814630892175,
1.2840254166877414840734205680624364583362808652814630892176,
1.2840254166877414840734205680624364583362808652814630892175]

parent( )

sage: R = RealField()
sage: a = R('1.2456')
sage: a.parent()
Real Field with 53 bits of precision

real( )

Return the real part of self.

(Since self is a real number, this simply returns self.)

round( )

Rounds self to the nearest integer. The rounding mode of the parent field has no effect on this function.

sage: RR(0.49).round()
0
sage: RR(0.5).round()
1
sage: RR(-0.49).round()
0
sage: RR(-0.5).round()
-1

sec( )

Returns the secant of this number

sage: RealField(100)(2).sec()
-2.4029979617223809897546004014

sech( )

Returns the hyperbolic secant of this number

sage: RealField(100)(2).sech()
0.26580222883407969212086273982

simplest_rational( )

Returns the simplest rational which is equal to self (in the SAGE sense). Recall that SAGE defines the equality operator by coercing both sides to a single type and then comparing; thus, this finds the simplest rational which (when coerced to this RealField) is equal to self.

Given rationals a/b and c/d (both in lowest terms), the former is simpler if b<d or if b==d and |a|<|c|.

The effect of rounding modes is slightly counter-intuitive. Consider the case of round-toward-minus-infinity. This rounding is performed when coercing a rational to a floating-point number; so the simplest_rational() of a round-to-minus-infinity number will be either exactly equal to or slightly larger than the number.

sage: RRd = RealField(53, rnd='RNDD')
sage: RRz = RealField(53, rnd='RNDZ')
sage: RRu = RealField(53, rnd='RNDU')
sage: def check(x):
...       rx = x.simplest_rational()
...       assert(x == rx)
...       return rx
sage: RRd(1/3) < RRu(1/3)
True
sage: check(RRd(1/3))
1/3
sage: check(RRu(1/3))
1/3
sage: check(RRz(1/3))
1/3
sage: check(RR(1/3))
1/3
sage: check(RRd(-1/3))
-1/3
sage: check(RRu(-1/3))
-1/3
sage: check(RRz(-1/3))
-1/3
sage: check(RR(-1/3))
-1/3
sage: check(RealField(20)(pi))
355/113
sage: check(RR(pi))
245850922/78256779
sage: check(RR(2).sqrt())
131836323/93222358
sage: check(RR(1/2^210))
1/1645504557321205859467264516194506011931735427766374553794641921
sage: check(RR(2^210))
1645504557321205950811116849375918117252433820865891134852825088
sage: (RR(17).sqrt()).simplest_rational()^2 - 17
-1/348729667233025
sage: (RR(23).cube_root()).simplest_rational()^3 - 23
-1404915133/264743395842039084891584
sage: RRd5 = RealField(5, rnd='RNDD')
sage: RRu5 = RealField(5, rnd='RNDU')
sage: RR5 = RealField(5)
sage: below1 = RR5(1).nextbelow()
sage: check(RRd5(below1))
31/32
sage: check(RRu5(below1))
16/17
sage: check(below1)
21/22
sage: below1.exact_rational()
31/32
sage: above1 = RR5(1).nextabove()
sage: check(RRd5(above1))
10/9
sage: check(RRu5(above1))
17/16
sage: check(above1)
12/11
sage: above1.exact_rational()
17/16
sage: check(RR(1234))
1234
sage: check(RR5(1234))
1185
sage: check(RR5(1184))
1120
sage: RRd2 = RealField(2, rnd='RNDD')
sage: RRu2 = RealField(2, rnd='RNDU')
sage: RR2 = RealField(2)
sage: check(RR2(8))
7
sage: check(RRd2(8))
8
sage: check(RRu2(8))
7
sage: check(RR2(13))
11
sage: check(RRd2(13))
12
sage: check(RRu2(13))
13
sage: check(RR2(16))
14
sage: check(RRd2(16))
16
sage: check(RRu2(16))
13
sage: check(RR2(24))
21
sage: check(RRu2(24))
17
sage: check(RR2(-24))
-21
sage: check(RRu2(-24))
-24

TESTS:

sage: RR('nan').simplest_rational()
Traceback (most recent call last):
...
ValueError: Cannot convert NaN or infinity to rational number
sage: RR('-infinity').simplest_rational()
Traceback (most recent call last):
...
ValueError: Cannot convert NaN or infinity to rational number

sin( )

Returns the sine of this number

sage: R = RealField(100)
sage: R(2).sin()
0.90929742682568169539601986591

sincos( )

Returns a pair consisting of the sine and cosine.

sage: R = RealField()
sage: t = R.pi()/6
sage: t.sincos()
(0.500000000000000, 0.866025403784439)

sinh( )

Returns the hyperbolic sine of this number

sage: q = RR.pi()/12
sage: q.sinh()
0.264800227602271

sqrt( )

The square root function.

Input:

extend
- bool (default: True); if True, return a square root in a complex field if necessary if self is negative; otherwise raise a ValueError
all
- bool (default: False); if True, return a list of all square roots.

sage: r = -2.0
sage: r.sqrt()
1.41421356237310*I

sage: r = 4.0
sage: r.sqrt()
2.00000000000000
sage: r.sqrt()^2 == r
True

sage: r = 4344
sage: r.sqrt()
2*sqrt(1086)

sage: r = 4344.0
sage: r.sqrt()^2 == r
True
sage: r.sqrt()^2 - r            
0.000000000000000

sage: r = -2.0
sage: r.sqrt()
1.41421356237310*I

str( )

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. e - symbol used in scientific notation; defaults to 'e' for base<=10, and '@' otherwise
truncate
- if True, round off the last digits in printing to lessen confusing base-2 roundoff issues.

sage: a = 61/3.0; a
20.3333333333333
sage: a.str(truncate=False)
'20.333333333333332'
sage: a.str(2)
'10100.010101010101010101010101010101010101010101010101'
sage: a.str(no_sci=False)
'2.03333333333333e1'        
sage: a.str(16, no_sci=False)
'1.4555555555555@1'
sage: b = 2.0^99
sage: b.str()
'6.33825300114115e29'
sage: b.str(no_sci=False)
'6.33825300114115e29'
sage: b.str(no_sci=True)
'6.33825300114115e29'
sage: c = 2.0^100
sage: c.str()
'1.26765060022823e30'
sage: c.str(no_sci=False)
'1.26765060022823e30'
sage: c.str(no_sci=True)
'1.26765060022823e30'
sage: c.str(no_sci=2)
'1267650600228230000000000000000.'
sage: 0.5^53
1.11022302462516e-16
sage: 0.5^54
5.55111512312578e-17

tan( )

Returns the tangent of this number

sage: q = RR.pi()/3
sage: q.tan()
1.73205080756888
sage: q = RR.pi()/6
sage: q.tan()
0.577350269189626

tanh( )

Returns the hyperbolic tangent of this number

sage: q = RR.pi()/11
sage: q.tanh()
0.278079429295850

trunc( )

Truncates this number

sage: (2.99).trunc()
2
sage: (-0.00).trunc()
0
sage: (0.00).trunc()
0

y0( )

Returns the value of the Bessel Y function of order 0 at self.

sage: R = RealField(53)
sage: R(2).y0()
0.510375672649745

y1( )

Returns the value of the Bessel Y function of order 1 at self.

sage: R = RealField(53)
sage: R(2).y1()
-0.107032431540938

yn( )

Returns the value of the Bessel Y function of order $ n$ at self.

sage: R = RealField(53)
sage: R(2).yn(3)
-1.12778377684043
sage: R(2).yn(-17)
7.09038821729481e12

zeta( )

Return the Riemann zeta function evaluated at this real number.

Note: PARI is vastly more efficient at computing the Riemann zeta function. See the example below for how to use it.

sage: R = RealField()
sage: R(2).zeta()
1.64493406684823
sage: R.pi()^2/6
1.64493406684823
sage: R(-2).zeta()
0.000000000000000
sage: R(1).zeta()
+infinity

Computing zeta using PARI is much more efficient in difficult cases. Here's how to compute zeta with at least a given precision:

sage: z = pari.new_with_bits_prec(2, 53).zeta(); z
1.644934066848226436472415167              # 32-bit
1.6449340668482264364724151666460251892    # 64-bit

Note that the number of bits of precision in the constructor only effects the internal precision of the pari number, not the number of digits that gets displayed. To increase that you must use pari.set_real_precision.

sage: type(z)
<type 'sage.libs.pari.gen.gen'>
sage: R(z)
1.64493406684823

Special Functions: __abs__,$ \,$ __complex__,$ \,$ __copy__,$ \,$ __eq__,$ \,$ __float__,$ \,$ __ge__,$ \,$ __gt__,$ \,$ __init__,$ \,$ __int__,$ \,$ __invert__,$ \,$ __le__,$ \,$ __long__,$ \,$ __lshift__,$ \,$ __lt__,$ \,$ __ne__,$ \,$ __pow,$ \,$ __pow__,$ \,$ __reduce__,$ \,$ __repr__,$ \,$ __rlshift__,$ \,$ __rpow__,$ \,$ __rrshift__,$ \,$ __rshift__,$ \,$ _complex_number_,$ \,$ _im_gens_,$ \,$ _integer_,$ \,$ _interface_init_,$ \,$ _latex_,$ \,$ _lshift_,$ \,$ _pari_,$ \,$ _rpy_,$ \,$ _rshift_

__abs__( )

__complex__( )

__copy__( )

Return copy of self - since self is immutable, we just return self again.

sage: a = 3.5
sage: copy(a) is  a
True

__float__( )

__int__( )

Returns integer truncation of this real number.

__invert__( )

__long__( )

Returns long integer truncation of this real number.

__lshift__( )

sage: 1.0 << 32
4.29496729600000e9
sage: 1.5 << 2.5
Traceback (most recent call last):
...
TypeError: unsupported operands for <<

__pow( )

__reduce__( )

sage: R = RealField(sci_not=1, prec=200, rnd='RNDU')
sage: b = R('393.39203845902384098234098230948209384028340')
sage: loads(dumps(b)) == b
True
sage: b = R(1)/R(0); b
+infinity
sage: loads(dumps(b)) == b
True
sage: b = R(-1)/R(0); b
-infinity
sage: loads(dumps(b)) == b
True
sage: b = R(-1).sqrt(); b
1.0000000000000000000000000000000000000000000000000000000000*I
sage: loads(dumps(b)) == b
True

__repr__( )

__rshift__( )

sage: 1024.0 >> 7
8.00000000000000
sage: 1.5 >> 2.5
Traceback (most recent call last):
...
TypeError: unsupported operands for >>

_complex_number_( )

_im_gens_( )

_integer_( )

If this floating-point number is actually an integer, return that integer. Otherwise, raise an exception.

sage: ZZ(237.0)
237
sage: ZZ(0.0/0.0)
Traceback (most recent call last):
...
TypeError: Attempt to coerce non-integral RealNumber to Integer
sage: ZZ(1.0/0.0)
Traceback (most recent call last):
...
TypeError: Attempt to coerce non-integral RealNumber to Integer
sage: ZZ(-123456789.0)
-123456789
sage: ZZ(RealField(300)(2.0)^290)
198929294563914656862152899258728336040182460318939086976185590757263798805
0133502132224
sage: ZZ(-2345.67)
Traceback (most recent call last):
...
TypeError: Attempt to coerce non-integral RealNumber to Integer

_interface_init_( )

Return string representation of self in base 10, avoiding scientific notation except for very large or very small numbers.

This is most likely to make sense in other computer algebra systems (this function is the default for exporting to other computer algebra systems).

sage: n = 1.3939494594
sage: n._interface_init_()
'1.3939494593999999'
sage: s1 = RR(sin(1)); s1
0.841470984807897
sage: s1._interface_init_()
'0.84147098480789650'
sage: s1 == RR(gp(s1))
True

_latex_( )

_lshift_( )

_pari_( )

Returns self as a Pari floating-point number.

sage: RR(2.0)._pari_()
2.000000000000000000

The current Pari precision affects the printing of this number, but Pari does maintain the same 250-bit number on both 32-bit and 64-bit platforms.

sage: RealField(250).pi()._pari_()
3.141592653589793238462643383               # 32-bit
3.1415926535897932384626433832795028842     # 64-bit
sage: RR(0.0)._pari_()
0.E-19
sage: RR(-1.234567)._pari_()
-1.2345669999999999700
sage: RR(2.0).sqrt()._pari_()
1.4142135623730951455
sage: RR(2.0).sqrt()._pari_().python()
1.41421356237309515
sage: RR(2.0).sqrt()._pari_().python().prec()
64
sage: RealField(70)(pi)._pari_().python().prec()
96                                         # 32-bit
128                                        # 64-bit
sage: for i in xrange(1, 1000):
...       assert(RR(i).sqrt() == RR(i).sqrt()._pari_().python())

_rpy_( )

Returns self.__float__() for rpy to convert into the appropriate R object.

sage: n = RealNumber(2.0)
sage: n._rpy_()
2.0
sage: type(n._rpy_())
<type 'float'>

_rshift_( )

See About this document... for information on suggesting changes.