0
$\begingroup$

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?

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

1 Answer 1

6
$\begingroup$

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 *)
$\endgroup$

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