4
$\begingroup$

Given 4 points as points = {{0, 4}, {1, 0}, {2, -1}, {3, 0}};. I want to find the coefficients of f[x_] := a x^3 + b x^2 + c x + d; and its plot.

How to solve this in Mathematica easily?

$\endgroup$
6
$\begingroup$

You can also use LinearSolve

A = CoefficientArrays[f@points[[All, 1]], {a, b, c, d}] //Last;
B = points[[All, 2]];

$A=\left( \begin{array}{cccc} 0 & 0 & 0 & 1 \\ 1 & 1 & 1 & 1 \\ 8 & 4 & 2 & 1 \\ 27 & 9 & 3 & 1 \\ \end{array} \right) \qquad B=\left( \begin{array}{c} 4 \\ 0 \\ -1 \\ 0 \\ \end{array} \right)$

LinearSolve[A, B]

{-(1/6), 2, -(35/6), 4}

$\endgroup$
5
$\begingroup$

Four points define the polynomial unambiguously, not fitting is necesary, so for an exact solution I would do a system of equations and use Solve

points = {{0, 4}, {1, 0}, {2, -1}, {3, 0}}
(* {{0, 4}, {1, 0}, {2, -1}, {3, 0}} *)

f[x_] := a x^3 + b x^2 + c x + d


(f[#1] == #2) & @@@ points
(* 
 {
   d == 4, 
   a + b + c + d == 0, 
   8 a + 4 b + 2 c + d == -1, 
   27 a + 9 b + 3 c + d == 0
  }
*)


Solve[
 (f[#1] == #2) & @@@ points
 , {a, b, c, d}
 ]
(* {{a -> -(1/6), b -> 2, c -> -(35/6), d -> 4}} *)
$\endgroup$
5
$\begingroup$
fit = FindFit[points, f[x], {a, b, c, d}, x]

{a -> -0.166667, b -> 2., c -> -5.83333, d -> 4.}

Plot[Evaluate[f[x] /. fit], {x, 0, 5}, 
 Epilog -> {PointSize[Large], Red, Point@points}]

enter image description here

To get exact results, you can use

Rationalize[fit] 

{a -> -(1/6), b -> 2, c -> -(35/6), d -> 4}

Alternatively, you can use Reduce or Solve (as in rhermans's answer) with alternative specification of the first argument:

ToRules @ Reduce[f /@ points[[All, 1]] == points[[All, 2]]] (* or *)
Solve[f /@ points[[All, 1]] == points[[All, 2]], {a, b, c, d}][[1]]

{a -> -(1/6), b -> 2, c -> -(35/6), d -> 4}

$\endgroup$
  • $\begingroup$ Could you make the coefficients in exact forms? $\endgroup$ – Friendly Ghost Aug 15 '18 at 7:51
  • $\begingroup$ @FriendlyGhost, you can use Rationalize[fit] to get {a -> -(1/6), b -> 2, c -> -(35/6), d -> 4} $\endgroup$ – kglr Aug 15 '18 at 7:54
  • $\begingroup$ @FriendlyGhost Four points define the polynomial unambiguously, so an exact solution is possible solving the system of equations, see my answer. $\endgroup$ – rhermans Aug 15 '18 at 10:12
2
$\begingroup$

You can use InterpolatingPolynomial:

Expand @ InterpolatingPolynomial[
    {{0,4},{1,0},{2,-1},{3,0}},
    x
]

4 - (35 x)/6 + 2 x^2 - x^3/6

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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