Ask Your Question
1

Unexpected behaviour of arbitrary precision real numbers

asked 6 years ago

fbarbuto gravatar image

updated 6 years ago

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

Preview: (hide)

1 Answer

Sort by » oldest newest most voted
3

answered 6 years ago

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

1.41421356237309514547
1.4142135623730950488
Preview: (hide)
link

Comments

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.

eric_g gravatar imageeric_g ( 6 years ago )

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 ( 6 years ago )

@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 gravatar imagenbruin ( 6 years ago )

@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 ( 6 years ago )

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

Stats

Asked: 6 years ago

Seen: 500 times

Last updated: May 19 '18