Home > database >  How to solve a cubic function without knowing the coefficients a b and c?
How to solve a cubic function without knowing the coefficients a b and c?

Time:06-23

Apology for this silly question. In the cubie function below (as from a school project), I am given the value for x and f(x) while coefficients a, b ,c and constant of d are unknown.

f(x)=ax^3 bx^2 cx d 

In such case, is there a way to find out a, b and c by using any python package? I found good amount of python tutorial for solving cubic function but they seem to mainly focus on solving x while a, b and c value are given.

CodePudding user response:

Here is an approach via sympy, Python's symbolic math library.

As an example, we are trying to find the formula for the sum of the first n triangular numbers. The triangular numbers (formula n*(n 1)/2) are 0, 1, 3, 6, 10, 15, 21, ..... The sums of the first n triangular numbers are thus 0, 1, 4, 10, 20, 35, 56, ....

from sympy import Eq, solve
from sympy.abc import a,b,c,d, x

formula = a*x**3   b*x**2   c*x   d  # general cubic formula
xs = [0, 1, 2, 3]  # some x values
fxs = [0, 1, 4, 10]  # the corresponding function values

sol = solve([Eq(formula.subs(x, xi), fx) for xi, fx in zip(xs, fxs)])
print(sol)  # {a: 1/6, b: 1/2, c: 1/3, d: 0}

You can use more x, fx pairs to check that a cubic formula suffices (this won't work with float values, as sympy needs exact symbolic equations).

Also sympy's interpolate can be interesting. This calculates a polynomial through some given points. Such code could look like:

from sympy import interpolate
from sympy.abc import x

xs = [0, 1, 2, 3]
fxs = [0, 1, 4, 10]
fx_dict = dict(zip(xs, fxs))
sol = interpolate(fx_dict, x)
print(sol)  # x**3/6   x**2/2   x/3
print(sol.factor())  # x*(x   1)*(x   2)/6
  • Related