# numerical_approx() weirdness?

Hi all:

I recently discovered that the numerical_approx() function (aliased as n()) does not perform as i expected. Is the following behavior intentional?

sage: x = pi.n(digits=3)
sage: print x, x.n(), QQ(x), QQ(x).n()
3.14 3.14160156250000 333/106 3.14150943396226


Where are the extra digits of x coming from to produce the last three results in the output above?

edit retag close merge delete

Let me elaborate. I expected that x = 3.14, so that x.n() = 3.14000000000000 and QQ(x) = 157/50. But x == 3.14 returns False, x.n() = 3.14160156250000 and QQ(x)= 333/106. Huh? Why are there more than 3 digits stored in x?

( 2011-08-10 00:45:39 +0200 )edit

Thanks for the clarification!

( 2011-08-12 13:24:34 +0200 )edit

Sort by » oldest newest most voted

When you write pi.n(digits=3), you do not get the rational number 314/100. What you get is a floating point number $x$ with a guarantee that $|\pi - x| \le 0.01$ (I believe this number also "knows" how many digits you care about; that's why print shows exactly 3 digits). Because floating point numbers are internally stored in base 2, it is impossible to represent 314/100 exactly.

more

Thanks, but i'm still wondering why i don't get the floating point number 3.14. For instance i get the correct n() expansion and rational with the following commands. sage: y = 3.14, sage: y.n(),QQ(y), (3.14000000000000, 157/50)

( 2011-08-11 22:41:54 +0200 )edit

I think that Jason's point is that with y=3.14, you get something with a lot of (base 2) precision, which can be nicely turned into a fraction, while when you limit it to 3 digits, this is the best you can get. At least, that's how I understand Jason's answer, and I think he's right.

( 2011-08-12 13:24:15 +0200 )edit

They don't come from anywhere special.

sage: x = pi.n(digits=3)
sage: y = QQ(x)
sage: type(y)
<type 'sage.rings.rational.Rational'>
sage: y.n()
3.14150943396226
sage: y.n(digits=100)
3.141509433962264150943396226415094339622641509433962264150943396226415094339622641509433962264150943
sage: n(333/106)
3.14150943396226


Once you turn x into a rational, it behaves as any other rational would. In particular, it has an eventually repeating decimal expansion, etc. The point is that you tried to turn a low-precision number into a rational, and this is what happens. Sorry that the rationals don't 'hold precision', but I don't think this would be intended.

more