1. 程式人生 > >Python計算一元函數的N次方多項式

Python計算一元函數的N次方多項式

道理 pri etime begin print mes reverse rom rev

第一種:
from datetime import datetime
#f(x)=a0+a1x+a2x*2+a3x**3+...
def f(a,x):

p=0
for i in range(0,len(a)):
    p=p+a[i]*((x)**i)

print(p)

a=[2,3,2,6,8,9,7,7,8,9,6,3,2,6,8,9,7,7,8,9,6,3,2,6,8,9,7,7,8,9,6,3,2,6,8,9,7,7,8,9,6,3,2,6,8,9,7,7,8,9,6,3,2,6,8,9,7,7,8,9,6,3,2,6,8,9,7,7,8,9,6,3,2,6,8,9,7,7,8,9,6,3,2,6,8,9,7,7,8,9,6,3,2,6,8,9,7,7,8,9,6,3,2,6,8,9,7,7,8,9,6,9,7,7,8,9,6,3,2,6,8,9,7,7,8,9,6,9,7,7,8,9,6,3,2,6,8,9,7,7,8,9,6,9,7,7,8,9,6,3,2,6,8,9,7,7,8,9,6,9,7,7,8,9,6,3,2,6,8,9,7,7,8,9,6,9,7,7,8,9,6,3,2,6,8,9,7,7,8,9,6,9,7,7,8,9,6,3,2,6,8,9,7,7,8,9,6]

x=1
begin = datetime.now() # 獲取當前datetime
beg_stamp=begin.timestamp()
for i in range(0,100):

t=f(a,x)

end = datetime.now() # 獲取當前datetime
end_stamp=end.timestamp() # 把datetime轉換為timestamp
print(end_stamp-beg_stamp)

第二種:
from datetime import datetime
#f(x)=a0+x(a1+x(...(an-1+x(an))))
def f(a,x):

p=a[-1]
for i in range(0,len(a)-1):
    b=list(reversed(a))
    p=b[i+1]+x*p

print(p)

a=[2,3,2,6,8,9,7,7,8,9,6,3,2,6,8,9,7,7,8,9,6,3,2,6,8,9,7,7,8,9,6,3,2,6,8,9,7,7,8,9,6,3,2,6,8,9,7,7,8,9,6,3,2,6,8,9,7,7,8,9,6,3,2,6,8,9,7,7,8,9,6,3,2,6,8,9,7,7,8,9,6,3,2,6,8,9,7,7,8,9,6,3,2,6,8,9,7,7,8,9,6,3,2,6,8,9,7,7,8,9,6,9,7,7,8,9,6,3,2,6,8,9,7,7,8,9,6,9,7,7,8,9,6,3,2,6,8,9,7,7,8,9,6,9,7,7,8,9,6,3,2,6,8,9,7,7,8,9,6,9,7,7,8,9,6,3,2,6,8,9,7,7,8,9,6,9,7,7,8,9,6,3,2,6,8,9,7,7,8,9,6,9,7,7,8,9,6,3,2,6,8,9,7,7,8,9,6]

x=1
begin = datetime.now() # 獲取當前datetime
beg_stamp=begin.timestamp()
for i in range(0,100 ):
t=f(a,x)
end = datetime.now() # 獲取當前datetime
end_stamp=end.timestamp() # 把datetime轉換為timestamp
print(end_stamp-beg_stamp)

註意:按道理第一種的時間復雜度為n平方,第二種為n
但是做出來的是第一種時間更短 ,不知道為什麽???試了很多次

Python計算一元函數的N次方多項式