# How do I get Mathematica to write the coefficients of polynomial as fractions rather than decimal expansions? [duplicate]

I am trying to have Mathematica find the polynomial of degree $n$ in a single variable which fits the given points $(x_1,y_1),\dots, (x_{n+1},y_{n+1})$. In the examples I am concerned with, the polynomials will always have rational number coefficients. Here is an example of the code I am using with $n=3$

Normal[LinearModelFit[{{0, 10}, {1, 35}, {2, 81}, {3, 154}}, x^Range[0, 3], x]]


10.+16.5 x+7.5 x^2+1. x^3


How do I get Mathematica to give the answer with the coefficients presented as fractions rather than as decimal expansions?

• Rationalize – Jason B. Jan 26 '17 at 23:12
• @JasonB. Thank you so much! – Seth Jan 26 '17 at 23:14
• This seems to work in many cases, but in some cases does not seem to be working. Is it possible that rounding errors are causing an inability to convert back to rational number form? I wonder if there is some way to avoid decimal digit expansions entirely. – Seth Jan 26 '17 at 23:28
• It's very possible you end up with a machine precision number that doesn't map to a fraction by Rationalize. Then you might have success rounding first. Don't know it can be avoided as linear model fit may use numeric methods – Jason B. Jan 26 '17 at 23:31
• Is there any way to fit a polynomial without using the linear model fit? From theory I know there is always a polynomial with rational coefficients which is a perfect fit, so it seems undesirable to use a method which is designed only to approximate data. – Seth Jan 26 '17 at 23:39

You can use the WorkingPrecision option of LinearModelFit:

Normal @ LinearModelFit[
{{0,10},{1,35},{2,81},{3,154}},
x^Range[0,3],
x,
WorkingPrecision->Infinity
]

(* 10+(33 x)/2+(15 x^2)/2+x^3 *)


or just use Rationalize afterwards (as mentioned by @Jason B.):

Normal @ LinearModelFit[{{0,10},{1,35},{2,81},{3,154}},x^Range[0,3],x]
Rationalize @ %

(* 10. +16.5 x+7.5 x^2+1. x^3 *)

(* 10+(33 x)/2+(15 x^2)/2+x^3 *)


or use InterpolatingPolynomial:

InterpolatingPolynomial[{{0,10},{1,35},{2,81},{3,154}},x]
Expand @ %

(* 10+x (25+(-1+x) (17/2+x)) *)

(* 10+(33 x)/2+(15 x^2)/2+x^3 *)