2

is it possible (in Python) to define a polynomial type of function that has changing amount of parameters? Number of parameters should change according to number of data series that I have in my input file.

Currently I have something like this:

def y(x, a0, x2, x3, x4):
    y = a0 + a1*x + a2*x**2 + a3*x**3
    return y

I could of course set parameters of higher order to zero by extra parameter but would there be some better way.

5 Answers5

3

You can loop over the arguments and evaluate the polynomial using Horners method, which is very efficient.

def y(x, *args):
  y = 0
  for a in reversed(args):
    y = y*x+a
  return y

You can find a heap more details about variable numbers of arguments in this question.

Community
  • 1
  • 1
Michael Anderson
  • 70,661
  • 7
  • 134
  • 187
3

an even simpler version using a generator expression

def y(x, *args):
  return sum(a * x ** i for i, a in enumerate(args))

and a Horner version using reduce

def horn(x, *args):
    return reduce(lambda y, a: y * x + a, reversed(args))
fbstj
  • 1,684
  • 1
  • 16
  • 22
1
def y(x, *args):
  y = 0
  i = 0

  for a in args:
    y += a * x ** i
    i += 1

  return y

print y(2, 1, 2) # 2 * 2 ^ 0 + 2 * 2 ^ 1 = 5
Danil Speransky
  • 29,891
  • 5
  • 68
  • 79
0

In this particular case it would be much cleaner to provide polynomial as a single argument, namely a list of coefficients:

 def eval_poly(x, poly):
     ....

 eval_poly(10, [1, 2, 3]) # evaluate (1 + 2x + 3x^2)(10)

This way you can handle polynomials like ordinary values, for example:

 def add_poly(p1, p2):
     """Add two polynomials together"""
     ...

 p1 = [1,2,3]
 p2 = [4,5,6]

 print eval_poly(10, add_poly(p1, p2))
georg
  • 211,518
  • 52
  • 313
  • 390
0

If you're working with data files and evaluating polynomials, you could probably benefit from using numpy, which also includes numpy.polyval for evaluating polynomials.

chthonicdaemon
  • 19,180
  • 2
  • 52
  • 66