前提・実現したいこと
remezアルゴリズムをpythonで表していますが、f(x)=sin(x)以外にもcos(x)やtan(x)など、他の関数もテストしたいです
発生している問題・エラーメッセージ
リストを使ったのですが、多分そのせいでこのエラーが出ます。他の方法でやるしかないのでしょうか? The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
該当のソースコード
Python
1def f(x): 2 return np.sin(x) 3lower=-np.pi 4upper=np.pi 5n=4 6reference_points=list(np.linspace(lower,upper,n+2)) 7 8 9 10class BestApprox: 11 tol=1.e-12 12 max_iter=100 13 a=[] 14 error_absolute_h=[] 15 def __init__(self,function): 16 self.f=function 17 def remez(self,reference=None): 18 self.name_dict={'lower':'lower bound','upper':'upper bound','n':'degree of polynomial'} 19 self.var_dict={'lower':None,'upper':None,'n':None} 20 if reference!=None: 21 if not isinstance(reference,list): 22 print("Oops! Initial guess not of 'list' data type.") 23 return 24 else: 25 self.reference=reference 26 self.var_dict['lower']=min(self.reference) 27 self.var_dict['upper']=max(self.reference) 28 self.n=len(self.reference)-2 29 elif reference==None: correct input 30 for i in self.var_dict: 31 while True: 32 try: 33 self.var_dict[str(i)]=float(input(f'Please specify {self.name_dict[str(i)]}: ')) 34 except ValueError: 35 print('Oops! Input non-numeric! Try again') 36 else: 37 break 38 self.n=int(self.var_dict['n']) # for better readability, n will also be stored as attribute instead of dict. 39 self.reference=list(np.linspace(self.var_dict['lower'],self.var_dict['upper'],self.n+2)) 40 41 error_absolute_h=[] 42 for i in range(self.max_iter): 43 Y=np.array([self.f(i) for i in self.reference]) 44 M=np.zeros((self.n+2)**2).reshape(self.n+2,self.n+2) 45 46 for i in range(self.n+2): 47 M[i,0]=1 48 M[i,-1]=(-1)**i 49 for i in range(self.n+2): 50 for j in range(1,self.n+1): 51 M[i,j]=(self.reference[i])**j 52 53 X=sp.solve(M,Y) 54 55 error_absolute_h.append(abs(X[-1])) 56 57 def p(x): 58 return sum(X[i]*x**i for i in range(self.n+1)) 59 60 error=([abs(f(x)-p(x)) for x in np.linspace(self.var_dict['lower'],self.var_dict['upper'],100)]) 61 max_error=max(error) 62 if max_error-abs(X[-1])<self.tol: 63 64 np.set_printoptions(precision=4) 65 print(f'convergense observed after {i+1} iterations, the coefficients of the polynomial that is the best approx of f are:{X[:-1]}') 66 67 print([(p(self.reference[i])-self.f(self.reference[i])) for i in range(len(self.reference))]) 68 print(error_absolute_h) 69 70 self.a=X[:-1] 71 break 72 index=error.index(max_error) 73 interval=list(np.linspace(self.var_dict['lower'],self.var_dict['upper'],100)) 74 eta=interval[index] 75 self.reference.append(eta) 76 self.reference.sort() 77 78 79 if self.reference[0]<=eta<=self.reference[-1]: 80 if ((self.f(eta)-p(eta))/(self.f(self.reference[self.reference.index(eta)-1])-p(self.reference[self.reference.index(eta)-1])))>0: 81 self.reference.remove(self.reference[self.reference.index(eta)-1]) 82 else: 83 self.reference.remove(self.reference[self.reference.index(eta)+1]) 84 elif eta<self.reference[0]: 85 if ((self.f(eta)-p(eta))/(self.f(self.reference[0])-p(self.reference[0]))): 86 self.reference.remove(self.reference[0]) 87 else: 88 self.reference.remove(self.reference[-1]) 89 elif eta>self.reference[-1]: 90 if ((self.f(eta)-p(eta))/(self.f(self.reference[-1])-p(self.reference[-1]))): 91 self.reference.remove(self.reference[-1]) 92 else: 93 self.reference.remove(self.reference[0]) 94 self.reference.sort() 95 Y[self.reference.index(eta)]=self.f(eta) 96 for i in range(1,self.n+1): 97 M[self.reference.index(eta),i]=(self.reference[self.reference.index(eta)])**i 98 99 100 def plot_f_remez(self): 101 x=np.linspace(self.var_dict['lower'],self.var_dict['upper'],100) 102 plt.plot(x,self.f(x)[0],'r',x,sum(self.a[i]*(x**i) for i in range(self.n+1)),'k:') 103 plt.show() 104 105 106def f(x):#テスト用にf(x)を再定義 107 func=[np.sin(x),np.cos(x),np.tan(x)]#このリストの中の関数でテストしたい 108 message="result with fx={func} is {result}." 109 for n in func: 110 return func 111 A=f(x) 112 print(message.format(fx=func,result=A)) 113 114lower=-np.pi 115upper=np.pi 116n=4 117reference_points=list(np.linspace(lower,upper,n+2)) 118 119x=np.linspace(lower,upper,100) 120message="result with x={x} is {result}." 121 122print(f(x)[0]) 123sin=BestApprox(f) 124sin.remez(reference_points) 125sin.plot_f_remez()
補足情報(FW/ツールのバージョンなど)
Python 3.9.5
あなたの回答
tips
プレビュー