Home > Software design >  How to use function a * x ^ m to approximate function with polyfit() or something similar in Python?
How to use function a * x ^ m to approximate function with polyfit() or something similar in Python?

Time:05-13

I have a set of data and I need to compare some approximation functions.

I used polyfit() for logarithmic and exponential fitting, but how can I use it for function a * x ^ m? It is a code for logarithmic regression:

x = numpy.array([1, 7, 20, 50, 79])
y = numpy.array([10, 19, 30, 35, 51])
numpy.polyfit(numpy.log(x), y, 1)
array([ 8.46295607,  6.61867463])
#y ≈ 8.46 log(x)   6.62

CodePudding user response:

The straightforward approach is to calculate the value of each power of the independent variable, and then do matrix multiplication with the coefficient:

>>> deg = 1
>>> x = np.array([1, 7, 20, 50, 79])
>>> y = np.array([10, 19, 30, 35, 51])
>>> log_x = np.log(x)
>>> p = np.polyfit(log_x, y, deg)
>>> p @ np.vstack([log_x ** i for i in range(deg, -1, -1)])
array([ 6.61867463, 23.08682675, 31.97142527, 39.72595348, 43.59711987])

A simpler approach is to use np.polyval, it is calculated through a loop:

>>> np.polyval(p, log_x)
array([ 6.61867463, 23.08682675, 31.97142527, 39.72595348, 43.59711987])

However, NumPy advocates the use of np.polynomial.Polynomial in the new code:

>>> p = np.polynomial.Polynomial.fit(log_x, y, deg)
>>> p(log_x)
array([ 6.61867463, 23.08682675, 31.97142527, 39.72595348, 43.59711987])
  • Related