[英]creating polynomial in python by reading coefficient from a file
我是python的新手。 我正在通過從文本文件中讀取多項式系數來創建多項式。 當我運行下面的代碼時,出現錯誤
“ TypeError:無法在標量上累積”
read_file = open('coefficient.txt','r')
coefficient = read_file.read()
p1 = poly1d([coefficient])
print(p1)
請輸入您的意見
您必須先將string
列表轉換為int
列表,然后再將其傳遞給poly1d:
from numpy import poly1d
read_file = open('coefficient.txt','r') # 1,1,0,1,0 store in file coefficient.txt
coefficient = read_file.readline().split(',') # coefficient =['1', '1', '0', '1', '0']
p1 = poly1d(map(int, coefficient)) #convert it to [1, 1, 0, 1, 0] with map for python2
#p1 = poly1d(list(map(int, coefficient))) #for python3
print(p1)
輸出:
4 3
1 x + 1 x + 1 x
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.