[英]Defining a grid using np.linspace and evaluating function over this grid
[英]Defining and evaluating a function of decreasing powers
我想寫一個 function 並且只輸入兩個參數: function 作為 integer 的度數和參數作為一個列表,並且能夠。
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
目前,我正在手動操作,對於高階 function 來說很乏味:
def func(t,a,b,c,d):
return a*pow(t,3)+b*pow(t,2)+c*t+d
您需要做的就是將系數列表作為……列表發送到您的 function。
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
class 最適合您。 它將幫助您定義 function,然后使用變量評估 function。 檢查此實現:
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
一種內置方法。 無需將度數作為參數傳遞,它將是系數列表的長度。 coefs
排列。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.