2

I have two arrays, say for ex:

x = ([0.004,0.005,0.006,0.007])
y = ([0.001,0.095,0.026,0.307])

I want to fit a polynomial of degree 3 but I don't really intend to have the constant term(intercept) in my fitted polynomial. what code would work for that case.

I was just simply trying

np.polyfit(x,y,3)

but it definitely returns 4 values.

Any leads are much appreciated.

Geet Sethi
  • 33
  • 1
  • 4
  • Yes you can use `curve_fit` but the most robust way to include a constraint when fitting a polynomial is by using the [Lagrange multiplier](https://en.wikipedia.org/wiki/Lagrange_multiplier). This is actually an existing question here on SO with an [excellent answer](https://stackoverflow.com/a/15196628/1622937). So, **voting to close this as duplicate**. – j-i-l Aug 30 '19 at 11:02
  • 1
    Possible duplicate of [How to do a polynomial fit with fixed points](https://stackoverflow.com/questions/15191088/how-to-do-a-polynomial-fit-with-fixed-points) – j-i-l Aug 30 '19 at 11:02

2 Answers2

2

Acutally in that case I'd go for scipy's curve_fit method and define my poly in a function.

import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt

#def a function
def f(x, a, b, c):
    return a*x**3 + b*x**2 + c*x

#convert your data to np arrays
xs = np.array([0.004,0.005,0.006,0.007])
ys = np.array([0.001,0.095,0.026,0.307])

#do the fitting
popt, pcov = curve_fit(f, xs, ys)

#plot the results
plt.figure()
plt.plot(xs,ys)
plt.plot(xs, f(xs, *popt))
plt.grid()
plt.show()

#the parameters
print(popt)
#outputs [ 7.68289022e+06 -7.34702147e+04  1.79106740e+02]
Péter Leéh
  • 2,069
  • 2
  • 10
  • 23
1

Use the curve_fit function from scipy, https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html

from scipy.optimize import curve_fit
import numpy as np

# convert your arrays to numpy arrays
x = np.array([0.004,0.005,0.006,0.007])
y = np.array([0.001,0.095,0.026,0.307])

# Choose the function form of your likings here
def f(x, a, b, c):
    return a * x + b * x ** 2 + c * x ** 3

# parameters and parameter covariances
popt, pcov = curve_fit(f, x, y)
a, b, c = popt
BramAppel
  • 1,346
  • 1
  • 9
  • 21