2
$\begingroup$

I'm trying to implement polynomial interpolation. My current implementation involves generating an expression that is the final equation that will be plotted. While plotting the function itself works fine, I also want to ListPlot the interpolation points (which will eventually be tuples stored in variable dots).

To achieve this, I attempted to do polyFunc[x_]=polyFunc which returns a Tag Plus in [expression] is Protected.

As an attempt to fix this, I also tried to store the expression in an auxiliary variable, polyFuncAux:

polyFuncAux[x_] = polyFunc

This returns no errors but yields the wrong answer. The x in the expression isn't substituted for the input value and is instead, appended to the end of the expression.

Ex:

Input: polyFuncAux[0] Output: [expression][0]

polyInterp[func_, interval_, degree_] :=
  Module[{xMatrix, yMatrix, polyFunc, polyFuncAux, newFunc, coeff, 
    line, dots},
   xMatrix = 
    Table[If[i == 0 && j == 0, 1, i^j], {i, interval[[1]], 
      interval[[2]], Abs[interval[[2]] - interval[[1]]]/degree}, {j, 
      0, degree}];
   xMatrix = Inverse[xMatrix];

   yMatrix = 
    Table[func[i], {i, interval[[1]], interval[[2]], 
      Abs[interval[[2]] - interval[[1]]]/degree}];

   coeff = xMatrix . yMatrix;

   polyFunc = Table[x^i, {i, 0, degree}];
   polyFunc = polyFunc*coeff;
   polyFunc = Total[polyFunc];
   polyFunc[x_] = polyFunc;

   (*
   line=Plot[{newFunc,func[x]},{x,interval[[1]],interval[[2]]},
   PlotStyle->{{Red,Thickness[0.006]},{Blue,Dashed}}];
   Show[line]
   *)
   ];
```
$\endgroup$
0

1 Answer 1

3
$\begingroup$

The relevant part of your code appears to be:

degree = 3;
polyFunc = Total[Table[x^i, {i, 0, degree}]];

Now you want to make polyFunc into an actual function. Try:

poly[x_] := Evaluate[polyFunc]

Now you can query poly for values like poly[1] or poly[2].

$\endgroup$
2
  • $\begingroup$ Attempting to evaluate poly[val] returns back the function regardless of whatever value is put in. Example case: Input:polyInterp[Function[x, 1/(1 + x^2)], {-5, 5}, 10] Output:1. - 0.674208 x^2 + 0.197376 x^4 - 0.0244118 x^6 + 0.00126697 x^8 - 0.0000226244 x^10 $\endgroup$
    – Jason Ham
    Commented Mar 8, 2023 at 1:36
  • $\begingroup$ Copy the code above, and start from a clean kernel. You will see that poly[1] and poly[2] return numerical values (4 and 15 in this case with degree = 3). $\endgroup$
    – bill s
    Commented Mar 8, 2023 at 1:46

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