2017-08-20 9 views
0

を変換することができる私はそれを解決するが、私が持っている私は線形方程式パイソン:TypeError例外:長さだけ-1配列は、Pythonスカラに

w0 + w1x1 + w2(x1)**2 + ... + wn(x1)**n = f(x1) 

のシステムを解くために必要FUNC

f(x) = sin(x/5.0)*exp(x/10.0) + 5*exp(-x/2.0) 

を有しますプロットの問題は、それが

from math import sin, exp 
from scipy import linalg 
import numpy as np 

b = [] 
def f(x): 
    return sin(x/5.0)*exp(x/10.0) + 5*exp(-x/2.0) 

for i in [1, 15]: 
    b.append(f(i)) 

A = [] 

for i in [1, 15]: 
    ij = [] 
    x0 = i ** 0 
    x1 = i ** 1 
    ij.append(x0) 
    ij.append(x1) 
    A.append(ij) 

matrix = np.array(A) 
b = np.array(b).T 

x = linalg.solve(matrix, b) 
from matplotlib import pyplot as plt 
plt.plot(x, f(x)) 

しかし、それは

を返します。
TypeError: only length-1 arrays can be converted to Python scalars 

どうすればこの問題を解決できますか?

答えて

1

math.sinおよびmath.expはスカラ入力が必要です。あなたは配列を渡す場合は、mathモジュールからTypeError

In [34]: x 
Out[34]: array([ 3.43914511, -0.18692825]) 

In [35]: math.sin(x) 
TypeError: only length-1 arrays can be converted to Python scalars 

from math import sin, exp負荷sinexpを取得し、グローバル名前空間の関数として定義されます。代わりにnumpyののsinexp機能を使用し、エラーを修正するには

def f(x): 
    return sin(x/5.0)*exp(x/10.0) + 5*exp(-x/2.0) 

:だからf(x)はnumpyの配列ですxsin機能のmathのバージョンを呼び出しています。

import numpy as np 
def f(x): 
    return np.sin(x/5.0)*np.exp(x/10.0) + 5*np.exp(-x/2.0) 
+0

どうしてですか? –

+1

標準ライブラリの 'math'モジュールの関数は、スカラーを入力とみなします。同等のNumPy関数は、NumPy配列で動作するように設計されています。 'x'はNumPy配列なので、' math.sin(x) 'ではなく' np.sin(x) 'を使う必要があります。 – unutbu

関連する問題