0
$\begingroup$

I'm just wondering why my function is not evaluating as I think it should. I put in the following:

dp = {{0, 71}, {1, 71}, {2, 71}, {3, 70}, {4, 69}, {5, 67}, {6,65}, {7, 63},
{8, 61}, {9, 60}, {10, 60}, {11, 61}, {12, 63},
{13,65}, {14, 66}, {15, 67}, {16, 67}, {16, 67}, {17, 66}, {18,65}, {19, 63},
{20, 60}, {21, 58}, {22, 56}, {23, 55}};
f = Fit[dp, {1, x, x^2, x^3, x^4, x^5, x^6, x^7}, x];
f[3]

but as output I get

(71.121 - 1.29633 x + 1.34837 x^2 - 0.504693 x^3 + 0.0700859 x^4 -
0.00447611 x^5 + 0.000134178 x^6 - 1.53469*10^-6 x^7)[3]

The output I want is the polynomial's value at x=3.

$\endgroup$

1 Answer 1

4
$\begingroup$

You can just make f a function of x in the first place.

f[x_] = Fit[dp, {1, x, x^2, x^3, x^4, x^5, x^6, x^7}, x]
f[3]
DownValues@f

71.121 - 1.29633 x + 1.34837 x^2 - 0.504693 x^3 + 0.0700859 x^4 - 0.00447611 x^5 + 0.000134178 x^6 - 1.53469*10^-6 x^7

70.4244

{HoldPattern[f[x_]] :> 71.121 - 1.29633 x + 1.34837 x^2 - 0.504693 x^3 + 0.0700859 x^4 - 0.00447611 x^5 + 0.000134178 x^6 - 1.53469*10^-6 x^7}

Also, I guess to actually answer your question of why it happened...It's because you were setting f as the polynomial expression itself, rather than a function of x. One could alternatively do

f = Fit[dp, {1, x, x^2, x^3, x^4, x^5, x^6, x^7}, x]
f /. x -> 3

71.121 - 1.29633 x + 1.34837 x^2 - 0.504693 x^3 + 0.0700859 x^4 - 0.00447611 x^5 + 0.000134178 x^6 - 1.53469*10^-6 x^7

70.4244

Or even

f = Function[x, Evaluate@Fit[dp, {1, x, x^2, x^3, x^4, x^5, x^6, x^7}, x]]
f[3]

Function[x, 71.121 - 1.29633 x + 1.34837 x^2 - 0.504693 x^3 + 0.0700859 x^4 - 0.00447611 x^5 + 0.000134178 x^6 - 1.53469*10^-6 x^7]

70.4244

$\endgroup$
3
  • $\begingroup$ That gives me a Protection error. (Oh, not when I restart. Never mind.) $\endgroup$
    – Jeh
    Commented Nov 5, 2018 at 21:45
  • $\begingroup$ Make sure to Clear@f first. $\endgroup$ Commented Nov 5, 2018 at 21:46
  • $\begingroup$ Gotcha. Thanks. $\endgroup$
    – Jeh
    Commented Nov 5, 2018 at 21:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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