2014-01-24 180 views
0

我想從一個多變量函數G定義一個變量g功能:如何從另一個多變量函數定義一個變量函數

def dG(thetaf,psi,gamma) : 
    return 0.35*(cos(psi))**2*(2*sin(3*thetaf/2+2*gamma)+(1+4*sin(gamma)**2)*sin(thetaf/2)-sin(3*thetaf/2))+sin(psi)**2*sin(thetaf/2) 

g = lambda thetaf: dG(thetaf,psi,gamma) 

不幸的是,這是不工作和錯誤我得到的是:

只有長度爲1的陣列可以被轉換到Python標量

+0

相關,可能是:在Python中的數組計算餘弦值(http://stackoverflow.com/q/21043644/846892) –

+0

只是爲了澄清它是參數標量還是數組? – cc7768

回答

1

你必須定義一些默認值。如果你使用關鍵字參數來做到這一點,你甚至不需要定義一個單獨的函數。

from numpy import sin, cos, arange 

def dG(thetaf,psi=0.5,gamma=1) : 
    return 0.35*(cos(psi))**2*(2*sin(3*thetaf/2+2*gamma)+(1+4*sin(gamma)**2)*sin(thetaf/2)-sin(3*thetaf/2))+sin(psi)**2*sin(thetaf/2) 

thetaf = arange(10) 
print dG(thetaf) 
>>> [ 0.4902 0.1475 0.5077 1.6392 1.757 0.4624 -0.472 -0.2416 -0.2771 -1.3398] 

您實際上可以定義一個單獨的函數,但使用關鍵字的默認值是更清潔的選擇。

g = lambda tf: dG(tf, 0.5, 1) 
g(thetaf) 
array([ 0.4902, 0.1475, 0.5077, 1.6392, 1.757 , 0.4624, -0.472 , 
     -0.2416, -0.2771, -1.3398]) 
+0

這不是我想要做的,我定義了我的函數dG,用3個變量thetaf,psi,gamma,並且我希望找到這個函數的根,例如: 'gamma = linspace(0,pi/2,nt)' 'psi = linspace(0,pi/2,np)' – Abdallah

+0

下面是我在腳本中寫的: 'def dG(thetaf,psi,gamma): 'return 0.35 *( COS(PSI))** 2 *(2 * SIN(3 * thetaf/2 + 2 *伽馬)+(1 + 4 * SIN(伽瑪)** 2)* SIN(thetaf/2)-sin(3 * (0,pi/2,nt)'+ sin(psi)** 2 * sin(thetaf/2)'gamma = linspace(0,π/ 2,nt)'' 'psi = linspace(0,pi/2,np)' 'x =零((nt,np))' 'for在列舉(i)中,列舉(gamma):'012',' ',其中' lambda thetaf:dG(thetaf,psi,gamma)' 'x [i,j] = optimize.brenth(g,-pi/2,pi/2)' – Abdallah

0

下一次,請將您的原始問題中的腳本包含在一個很好的格式中。它使幫助更快。

我認爲這只是一個簡單的錯誤。你可以分別得到theta和phi gamma和psi,但是你永遠不會使用它們。你的意思是用g作爲你的參數嗎?如果是這樣,那麼就應該是這個樣子

from numpy import sin, cos, arange, linspace, pi, zeros 
import scipy.optimize as opt  

def dG(thetaf, psi, gamma): 
    return 0.35*(cos(psi))**2*(2*sin(3*thetaf/2+2*gamma)+(1+4*sin(gamma)**2)*sin(thetaf/2)-sin(3*thetaf/2))+sin(psi)**2*sin(thetaf/2)  

nt = 100 
np = 100 
gamma = linspace(0, pi/2, nt) 
psi = linspace(0, pi/2, np) 
x = zeros((nt, np)) 
for i, theta in enumerate(gamma): 
    for j, phi in enumerate(psi): 
     print('i = %d, j = %d') %(i, j) 
     g = lambda thetaf: dG(thetaf,phi,theta) 
     x[i,j] = opt.brenth(g,-pi/2,pi/2) 
+0

是的,這是我的錯, 通常它是gammas = linespace (ps) 伽馬在enemurate(gammas),psi在枚舉(psis) 我怎麼能繪製解決方案x在3D計劃(gammas,psis)使用mplot3d @ cc7768 – Abdallah

+0

那麼以上是您的原始問題的答案。請註冊並接受。開始一個新的問題,並顯示你已經嘗試過,我可以幫助。 – cc7768

相關問題