Broadcasting a python function on to numpy arrays

前端 未结 3 1300
鱼传尺愫
鱼传尺愫 2020-12-15 11:08

Let\'s say we have a particularly simple function like

import scipy as sp
def func(x, y):
   return x + y

This function evidently works for

3条回答
  •  执笔经年
    2020-12-15 11:14

    For this special case, you could also write a function that operates on both, NumPy arrays and plain Python floats:

    def func2d(x, y):
        z = 2.0 * (x > y) - 1.0
        z *= y
        return x + z
    

    This version is also more than four times as fast as unutbu's func2a() (tested with N = 100).

提交回复
热议问题