# Unexpected behaviour of arbitrary precision real numbers

I've been trying to use arbitrary precision real numbers and I'm a bit confused. The simple snippet below illustrates my point:

R = RealField(200)
z = R(2.0)
print '%.20f' % (z.sqrt())


I should get (or that's what I was expecting) 1.41421356237309504880, but instead I got 1.41421356237309514547 (a disagreement in the last five decimal places). Where am I goofing up? You see, it's a quite simple code. How could I fix it in order to obtain the desired/expected result?

Thanks in advance for any light shed on this matter.

Fausto

edit retag close merge delete

Sort by » oldest newest most voted

%.20f' % (z.sqrt()) is a Python string expression using Python numeric formatting, which is unaware of Sage's arbitrary precision numericals ; your arbitrary precision value is therefore first converted in a Python float before being passed tro Python's numerical formatting. Use Sage's numerical formatting to obtain a string representationof the desired precisin.

In Sagecell :

R = RealField(200)
z = R(2.0)
print '%.20f' % (z.sqrt())
print repr(z.sqrt().n(digits=20))

1.41421356237309514547
1.4142135623730950488

more

1

As a side remark, the modern way of formatting fails here:

sage: '{:.20f}'.format(z.sqrt())
ValueError: Unknown format code 'f' for object of type 'str'


This means that for format no prior conversion to float is performed.

That worked, thanks! I was suspecting that the formatted print command should be blamed for that. Yet, the following two lines work nicely on Sage's notebook, too:

W = RealField(200)
print W.pi()


and repr() seems not to be necessary in this case. Too much to learn. :-)

@eric_g: indeed. In fact, if we would implement a __format__ method the sage multiprecision floats could participate in the "{}".format(...)game. https://trac.sagemath.org/ticket/7682 seems to be going in that direction.

@nbruin: indeed, this would be nice! In the current state, I guess a newcomer would be surprised that she/he cannot use format to display an element of RR or RDF.