Ask Your Question

numerical_approx() weirdness?

asked 2011-08-09 15:51:39 -0600

araichev gravatar image

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 flag offensive 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?

araichev gravatar imagearaichev ( 2011-08-09 17:45:39 -0600 )edit

Thanks for the clarification!

kcrisman gravatar imagekcrisman ( 2011-08-12 06:24:34 -0600 )edit

2 answers

Sort by ยป oldest newest most voted

answered 2011-08-11 06:53:12 -0600

Jason Bandlow gravatar image

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.

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

araichev gravatar imagearaichev ( 2011-08-11 15:41:54 -0600 )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.

kcrisman gravatar imagekcrisman ( 2011-08-12 06:24:15 -0600 )edit

answered 2011-08-09 16:25:32 -0600

kcrisman gravatar image

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()
sage: y.n(digits=100)
sage: n(333/106)

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.

edit flag offensive delete link more

Your Answer

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

Add Answer

Question Tools


Asked: 2011-08-09 15:51:39 -0600

Seen: 183 times

Last updated: Aug 11 '11