4

我有一个依赖于几个变量的函数,比如说y=f(x1,x2,x3,x4). 如果每个变量都是一个简单的数字,那么结果应该是一个普通的数字。如果其中一个变量是一个数组,我需要结果也是一个数组。依此类推:如果两个变量是数组,我需要结果是一个二维数组。等等。

例子:

def f(x1,x2,x3,x4):
    y=x1*x2/(x3+x4)
    return y

x1=1.0
x2=2.0
x3=3.0
x4=4.0
f(x1,x2,x3,x4)
# should give 2.0/7.0 = 0.2857...

x3=array([1.0,2.0,3.0,4.0,5.0])
f(x1,x2,x3,x4)
# should give a one-dimensional array with shape (5,)

x4=array([10.0,20.0,30.0,40.0,50.0,60.0,70.0])
f(x1,x2,x3,x4)
# should give a two-dimensional array with shape (5,7)

怎么做?(为了让我的程序的非 Python 读者尽可能清楚?)

4

2 回答 2

2

正确的方法是传入形状正确的数据。如果你想要一个二维结果,你应该传入二维数组。这可以通过np.newaxis.

import numpy as np

def f(x1,x2,x3,x4):
    y = x1*x2/(x3+x4)
    return y

x1 = 1.0
x2 = 2.0
x3 = 3.0
x4 = 4.0
print f(x1,x2,x3,x4)

x3 = np.array([1.0,2.0,3.0,4.0,5.0])
print f(x1,x2,x3,x4)

x3 = x3[:, np.newaxis]
x4 = np.array([10.0,20.0,30.0,40.0,50.0,60.0,70.0])
x4 = x4[np.newaxis, :]
print f(x1,x2,x3,x4)

当然,您提出问题的方式有点模棱两可,为什么您应该期望得到一个 array shape(5, 7)而不是 array shape (7, 5)

于 2013-12-20T19:24:44.123 回答
0

您可能会考虑使用 @when 来适当地定义函数。

例如:

# Case for single values
@when(int, int, int, int)
def f(x1,x2,x3,x4):
    y = x1*x2/(x3+x4)
    return y

# Case for 1D arrays
@when(list, list, list, list)
def f(x1,x2,x3,x4):
    y = []
    for i in range(len(x1)):
        y.append(x1[i]*x2[i]/(x3[i]+x4[i]))
    return y
于 2013-12-20T19:28:15.703 回答