Ask Your Question
1

Unexpected behaviour of arbitrary precision real numbers

asked 2018-05-19 02:26:56 +0200

fbarbuto gravatar image

updated 2018-05-19 02:29:08 +0200

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 flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2018-05-19 11:03:27 +0200

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
edit flag offensive delete link more

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 ( 2018-05-19 13:55:48 +0200 )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 17:45:50 +0200 )edit

@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 ( 2018-05-20 08:16:22 +0200 )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 17:43:33 +0200 )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

Stats

Asked: 2018-05-19 02:26:56 +0200

Seen: 393 times

Last updated: May 19 '18