Ask Your Question

Unexpected behaviour of arbitrary precision real numbers

asked 2018-05-18 19:26:56 -0500

fbarbuto gravatar image

updated 2018-05-18 19:29:08 -0500

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.


edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2018-05-19 04:03:27 -0500

Emmanuel Charpentier gravatar image

%.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))

edit flag offensive delete link more



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.

eric_g gravatar imageeric_g ( 2018-05-19 06:55:48 -0500 )edit

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. :-)

fbarbuto gravatar imagefbarbuto ( 2018-05-19 10:45:50 -0500 )edit

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

nbruin gravatar imagenbruin ( 2018-05-20 01:16:22 -0500 )edit

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

eric_g gravatar imageeric_g ( 2018-05-20 10:43:33 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2018-05-18 19:26:56 -0500

Seen: 105 times

Last updated: May 19