Home > Enterprise >  Defining and evaluating a function of decreasing powers
Defining and evaluating a function of decreasing powers

Time:09-09

I would like to write a function and input only two parameters: the degree of the function as an integer and the parameters as a list, and be able to evaluate it.

def func(degree: int, params: list) -> Object
    pass
In: f = func( 3, [3, 2, -1, 8] )
In:f
Out: 3*x**3   2*x**2 - 1*x   8

In:f(3)
Out: 104

Currently, I'm doing manually and it's tedious for higher-order function:

def func(t,a,b,c,d):
    return a*pow(t,3) b*pow(t,2) c*t d

CodePudding user response:

SymPy's Poly pretty much has all the batteries you need:

enter image description here

CodePudding user response:

All you need to do is send the list of coefficients to your function as ... a list.

def evaluate_polynomial(x : int, a : list):
    result = 0
    n = len(a)
    for i in range(n):
        result  = a[i] * x**(n-i-1)
    return result

assert evaluate_polynomial(3, [3, 2, -1, 8]) == 104
assert evaluate_polynomial(3, [-1, 4, -3, 1, -4, 3, 2, -1, 8]) == 23

CodePudding user response:

A class will work best for you. It will help you to define a function, then evaluate the function using a variable. Check this implementation:

class CreateFunction:
    def __init__(self, degree: int, weights: list):
        self.degree = degree
        self.weights = weights
        self.powers = [i for i in range(self.degree,-1,-1)]

        # making powers of extreme right variables 0
        # if the list containing weights has more weights
        # than the list containing powers (exponents)
        if len(self.weights)>len(self.powers):
            difference = len(self.weights) - len(self.powers)
            additional_powers = [0 for i in range(difference)]
            self.powers  = additional_powers


    def evaluate(self, variable: int):
        sum=0
        for (w, p) in zip(self.weights, self.powers):
            sum  = w*variable**p
        return sum

func = CreateFunction(3, [3, 2, -1, 8])
out1 = func.evaluate(3)
print(f'out1={out1}')

out2 = func.evaluate(5)
print(f'out2={out2}')

func2 = CreateFunction(4, [3, 2, -1, 8, 17])
out3 = func2.evaluate(7)
print(f'out3={out3}')

output

out1=104
out2=428
out3=7913

CodePudding user response:

A build-in approach. No need to pass the degree as parameter, it will be the length of the list of coefficients. The coefs are ordered from highest to lower degree.

def polynomial(coefs):
    return lambda x: sum(c * x**(index-1) for c, index in  zip(coefs, range(len(coefs), -1, -1)))

p = polynomial([3, 2, -1, 8])

print(p(3))
#104
  • Related