Home >Backend Development >Python Tutorial >How to define piecewise functions in Python
How does Python define piecewise functions? The following is a piecewise function:
At the beginning, I wrote a simple version of log_norm0, which can only be performed element by element. Needless to say, vectors with a large number of elements will definitely slow down.
Later I thought of using an indicator function to distinguish the two situations of segmentation, and I got log_norm1. However, this situation is quite special and cannot be successfully constructed every time.
Related recommendations: "Python Video Tutorial"
Finally, I found that there is a function piecewise(x, condlist, funclist, *args, **kw) in numpy, It is specially used to construct segmented functions, x is the input, condlist represents the condition of segmentation, and funclist represents the processing function of the corresponding segment. This gives us log_norm2.
# elementwise def log_norm0(x): if x >= 0: return np.log(x + 1) else: return - np.log(- x + 1) # indicator def log_norm1(x): # ind = np.where(x > 0, 1, 0) ind = (x > 0) return np.log(x * ind + 1) - np.log(- x * (1.0 - ind) + 1) # numpy.piecewise() def log_norm2(x): return np.piecewise(x, [x >= 0, x < 0], [lambda x: np.log(1 + x), lambda x: - np.log(1 - x)])
Finally, observe the running time of each function.
tic = time.time() for i in range(x.size): y[i] = log_norm0(x[i]) toc = time.time() print('log0: ', toc - tic) tic = time.time() y = log_norm1(x) toc = time.time() print('log1: ', toc - tic) tic = time.time() z = log_norm2(x) toc = time.time() print('log2: ', toc - tic)
Observation results show that the method using the indicator function is still the fastest, but it is not much different from piecewise.
log0: 33.59282732009888 log1: 0.4863457679748535 log2: 0.5942573547363281
The above is the detailed content of How to define piecewise functions in Python. For more information, please follow other related articles on the PHP Chinese website!