python,polynomials , Create a polynomial of arbitrary degree in python

## Question:

Tag: python,polynomials

I would like to use a polynomial function of the type ax +bx^2+c*x^3+... to fit some data using scipy.optimize.curve_fit.

I managed to do it fine but my problem is that I would like the user to be able to enter the degree of the polynomial for the fit and nothing more. I haven't been able to find an easy way to generate a polynomial of degree n without specifying the coefficients in python. Can anyone help me?

Thanks!

Yes, you can create an arbitrary degree polynomial, it will compute up to however many coefficients you give it. You want to make sure to give it `d+1` coefficients if the user wants a polynomial of degree `d`. You can convince `curve_fit` to give it `d+1` coefficients if you make sure the initial guess has length `d+1`.

``````from scipy.optimize import curve_fit

# get xdata, ydata, and desired degree d from user

def arbitrary_poly(x, *params):
return sum([p*(x**i) for i, p in enumerate(params)])

popt, pcov = curve_fit(arbitrary_poly, xdata, ydata, p0=[1]*(d+1))
``````

The `[1]*(d+1)` is just one possible initial guess that has the correct length. If you're doing something smarter to pick the initial guess, you should do that, and you probably already have to make sure it has the correct length. If you're not figuring out your own `p0`, `curve_fit` defaults to an array of all 1s, assuming it can figure out the appropriate length. Since `arbitrary_poly` is specifically designed to take any number of params, and hence will not allow `curve_fit` to figure out what the expected length is, the default behaviour would raise an exception. That is fixed by giving it an explicit array of all 1s, of the right length.

# Related:

## Pandas Dataframe Complex Calculation

python,python-2.7,pandas,dataframes
I have the following dataframe,df: Year totalPubs ActualCitations 0 1994 71 191.002034 1 1995 77 2763.911781 2 1996 69 2022.374474 3 1997 78 3393.094951 I want to write code that would do the following: Citations of currentyear / Sum of totalPubs of the two previous years I want something to...

## Matplotlib: Plot the result of an SQL query

python,sql,matplotlib,plot
from sqlalchemy import create_engine import _mssql from matplotlib import pyplot as plt engine = create_engine('mssql+pymssql://**:****@127.0.0.1:1433/AffectV_Test') connection = engine.connect() result = connection.execute('SELECT Campaign_id, SUM(Count) AS Total_Count FROM Impressions GROUP BY Campaign_id') for row in result: print row connection.close() The above code generates an array: (54ca686d0189607081dbda85', 4174469) (551c21150189601fb08b6b64', 182) (552391ee0189601fb08b6b73', 237304) (5469f3ec0189606b1b25bcc0',...

## group indices of list in list of lists

python,list
I am looking for an elegant solution for the following problem. I have a list of ints and I want to create a list of lists where the indices with the same value are grouped together in the order of the occurrences of said list. [2, 0, 1, 1, 3,...

## Spring-integration scripting with Python

python,spring-integration,jython
I'm trying to use Python with spring-integration and jython-standalone-2.7.0: Here is my application context: <int:inbound-channel-adapter id="in" channel="exampleChannel" > <int:poller fixed-rate="1000" /> <int-script:script lang="python" location="script/message.py" /> </int:inbound-channel-adapter> <int:channel id="exampleChannel" /> <int-ip:udp-outbound-channel-adapter id="udpOut" channel="exampleChannel" host="192.168.0.1" port="11111" /> Here is my script in Python: print "Python"...

## Python: can't access newly defined environment variables

python,bash,environment-variables
I can't access my env var: import subprocess, os print os.environ.get('PATH') # Works well print os.environ.get('BONSAI') # doesn't work But the env var is well added in my /home/me/.bashrc: BONSAI=/home/me/Utils/bonsai_v3.2 export BONSAI And I can access this env var from a new terminal....

## SQLAlchemy. 2 different relationships for 1 column

python,sqlalchemy
I have a simple many-to-many relationship with associated table: with following data: matches: users: users_mathces: ONE user can play MANY matches and ONE match can involve up to TWO users I want to realize proper relationships in both "Match" and "User" classes users_matches_table = Table('users_matches', Base.metadata, Column('match_id', Integer, ForeignKey('matches.id', onupdate="CASCADE",...