Abdallah
Abdallah

Reputation: 81

How to define a one variable function from another multivariable function

I am trying to define a one variable g function from a multivariable function 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)

unfortunately this is not working and the error i receive is that :

only length-1 arrays can be converted to Python scalars

Upvotes: 0

Views: 571

Answers (2)

cc7768
cc7768

Reputation: 325

Next time, please include the script in your original question in a nice format. It makes helping go faster.

I think it is just a simple mistake. You get theta and phi out of gamma and psi respectively, but then you never use them. Did you mean to use those as your parameters in g? If so, then it should look something like this

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)

Upvotes: 0

Michael
Michael

Reputation: 7736

You have to define some default values. If you do this by using keyword arguments, you don't even need to define a separate function.

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]

You actually can define a separate function, but using keyword defaults is the cleaner alternative.

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])

Upvotes: 1

Related Questions