Automatic array calculation in python (numpy)

I have a function that depends on several variables, say y=f(x1,x2,x3,x4). If each variable is a prime, then the result should be a prime. If one of the variables is an array, I need the result to be also an array. And so on: if two variables are arrays, I need the result to be a two-dimensional array. Etc.

Example:

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)

How to do it? (To be as clear as possible to a non-Python reader of my program?)

+4
source share
2 answers

- . 2d, 2d . 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)

, , , (5, 7), (7, 5).

+2

@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
0

All Articles