使用python / numpy评估数组上的多变量函数

时间:2016-05-24 15:22:46

标签: python arrays numpy

我知道python允许在numpy数组f(x)上快速评估实值,一个变量函数xarr = np.array([x0,x1,...xN])

f(xarr) = np.array([f(x0), f(x1), ..., f(xN)])

但是,对于多变量函数来说,这似乎不会在语法方面起作用。假设我有一个实值函数f(x,y),其中x和y是两个实数。是否有正确的语法来评估函数,比如[(0,0), (0,1), (1,0), (1,1)],避免循环(在python上总是很慢......)?

编辑:以下是涉及的功能:

我所指的5变量函数是:

def chisqr(BigOmega, inc, taustar, Q0, U0):
      QU = QandU(nusdata, BigOmega, inc, taustar, Q0, U0)
      Q = QU[:,0]
      U = QU[:,1]
      return 1./(2.*N) * (np.sum(((Q - Qs)/errQs)**2.) + np.sum(((U - Us)/errUs)**2.))

其中nusdata, Qs,Us是在调用函数之前定义的数组。该函数调用以下函数:

def QandU(nu, BigOmega, inc, taustar, Q0, U0):
      lambdalong = nu+omega-np.pi/2.
      tau3 = taustar * ((1+ecc*np.cos(nu))/(1-ecc**2.))**gamma
      delQ = -tau3 * (1+np.cos(inc)*np.cos(inc))*(np.cos(2.*lambdalong) np.sin(inc)*np.sin(inc))
      delU = -2*tau3*np.cos(inc)*np.sin(2*lambdalong)
      Q = Q0 + delQ*np.cos(BigOmega) - delU * np.sin(BigOmega)
      U = U0 + delQ*np.sin(BigOmega) + delU * np.cos(BigOmega)
      bounds = (inc < 0) or (inc > np.pi/2.) or (BigOmega < -2*np.pi) or (BigOmega > 2*np.pi) or (taustar < 0.) or (taustar > 1.)
      if bounds:
            Q = 10E10
            U = 10E10
      #return U
      return np.column_stack((Q,U))

所有不属于函数参数的变量都是在函数外定义的。

1 个答案:

答案 0 :(得分:2)

使用一个简单的例子:

np.array([0, 1, 2, 1])
f(xarr) = np.array([f(x0), f(x1), ..., f(xN)])

您的陈述f一般不正确。这完全取决于QandU的定义。如果f只包含算术运算,那么它是真的,但一般来说,它不是。

您的def QandU(nu, BigOmega, inc, taustar, Q0, U0): # left unchanged lambdalong = nu+omega-np.pi/2. tau3 = taustar * ((1+ecc*np.cos(nu))/(1-ecc**2.))**gamma delQ = -tau3 * (1+np.cos(inc)*np.cos(inc))*(np.cos(2.*lambdalong) np.sin(inc)*np.sin(inc)) delU = -2*tau3*np.cos(inc)*np.sin(2*lambdalong) Q = Q0 + delQ*np.cos(BigOmega) - delU * np.sin(BigOmega) U = U0 + delQ*np.sin(BigOmega) + delU * np.cos(BigOmega) # or doesn't vectorize, use bitwise or bounds = (inc < 0) | (inc > np.pi/2.) | (BigOmega < -2*np.pi) | (BigOmega > 2*np.pi) | (taustar < 0.) | (taustar > 1.) # if statements also don't vectorize Q[bounds] = 10E10 U[bounds] = 10E10 # stacking is more trouble that it's worth return Q, U 功能几乎应按预期工作:

chisqr

您的axis=函数可能需要将sum参数传递给void gvReport_Sorting(object sender, GridViewSortEventArgs e) { System.Data.DataTable dataTable = ViewState["dataTable"] as System.Data.DataTable; string sortDirection = (ViewState["sortDirection"].ToString() == "ASC" ? "DESC" : "ASC"); ViewState["sortDirection"] = sortDirection; if (dataTable != null) { System.Data.DataView dataView = new System.Data.DataView(dataTable); dataView.Sort = String.Format("{0} {1}", e.SortExpression, sortDirection); gvReport.DataSource = dataView; gvReport.DataBind(); } } ,具体取决于您要求的总和。