Python實現多項式計算的四種方法
阿新 • • 發佈:2019-01-06
問題描述
分別實現多項式求值的四種運算,若針對不同規模的輸入值
解題方法
需要用四種不同的方法實現對多項式的求值,這裡採用的是直接代入以及三種不同的遞迴演算法。三種不同的遞迴思想分別為:
iQ
具體程式碼
import numpy as np
import time
import math
import random
# root = np.array([1, 2, 1])
# p = np.poly1d(root)
# r = np.roots(p)
# print(r)
n = [10,50,100,150,200,300,400,500]
x = 1.2 #將多項式中x的值設為1.2
Sum_time1 = []
Sum_time2 = []
Sum_time3 = []
Sum_time4 = []
for ele in n:
a = np.random.random(ele)
p = np.poly1d(a)
time_start = time.time()
temp = np.polyval(p, x)
time_end = time.time()
Sum_time1.append(time_end - time_start)
temp = float('Inf')
time_start = time .time()
for i in range(0, ele, 1):
temp = temp + a[i] * x**i
time_end = time.time()
Sum_time2.append(time_end - time_start)
# temp = int()
time_start = time.time()
q = 1
for i in range(0, ele, 1):
q = q * x
temp = temp + a[i] * q
time_end = time.time()
Sum_time3.append(time_end - time_start)
#temp = int()
time_start = time.time()
for i in range(0, ele, 1):
temp = temp * x + a[ele - i - 1]
time_end = time.time()
Sum_time4.append(time_end - time_start)
print(Sum_time1)
print(Sum_time2)
print(Sum_time3)
print(Sum_time4)