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

Mathematica gives the following answer:

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?

  • 1
    $\begingroup$ Rationalize $\endgroup$ – Jason B. Jan 26 '17 at 23:12
  • $\begingroup$ @JasonB. Thank you so much! $\endgroup$ – Seth Jan 26 '17 at 23:14
  • $\begingroup$ 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. $\endgroup$ – Seth Jan 26 '17 at 23:28
  • $\begingroup$ 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 $\endgroup$ – Jason B. Jan 26 '17 at 23:31
  • $\begingroup$ 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. $\endgroup$ – Seth Jan 26 '17 at 23:39

You can use the WorkingPrecision option of LinearModelFit:

Normal @ LinearModelFit[

(* 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:

Expand @ %

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

(* 10+(33 x)/2+(15 x^2)/2+x^3 *)
|improve this answer|||||

Not the answer you're looking for? Browse other questions tagged or ask your own question.