How to define piecewise functions in Python

爱喝马黛茶的安东尼
Release: 2019-08-02 14:11:41
Original
16671 people have browsed it

How to define piecewise functions in Python

How does Python define piecewise functions? The following is a piecewise function:

How to define piecewise functions in Python

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)])
Copy after login

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(&#39;log0: &#39;, toc - tic)
tic = time.time()
y = log_norm1(x)
toc = time.time()
print(&#39;log1: &#39;, toc - tic)
tic = time.time()
z = log_norm2(x)
toc = time.time()
print(&#39;log2: &#39;, toc - tic)
Copy after login

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!