How to write python piecewise function?

coldplay.xixi
Release: 2020-06-19 13:14:49
Original
24827 people have browsed it

How to write python piecewise function?

How to write python piecewise function?

How to write piecewise functions in Python:

1. Draw piecewise functions: y=4sin(4πt)-sgn(t-0.3)- sgn(0.72-t)

Code:

#!/usr/bin/python
# -*- coding:utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
#绘制分段函数:y=4sin(4πt)-sgn(t-0.3)-sgn(0.72-t)
def sgn(x):
    if x > 0:
        return 1
    elif x < 0:
        return -1
    else:
        return 0
t = np.arange(0, 1, 0.01)
y = []
for i in t:
    y_1 = 4 * np.sin(4 * np.pi * i) - sgn(i - 0.3) - sgn(0.72 - i)
    y.append(y_1)
plt.plot(t, y)
plt.xlabel("t")
plt.ylabel("y")
plt.title("Heavsine")
plt.show()
Copy after login

How to write python piecewise function?

How to write python piecewise function?

2. Use Matplotlib to draw piecewise functions:

Code:

#!/usr/bin/python
# -*- coding:utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
def sgn(value):
    if value < 4:
        return 20
    else:
        return 15
plt.figure(figsize=(6, 4))
x = np.linspace(0, 8, 100)
y = np.array([])
for v in x:
    y = np.append(y, np.linspace(sgn(v), sgn(v), 1))
l = plt.plot(x, y, &#39;b&#39;, label=&#39;type&#39;)
plt.legend()
plt.show()
Copy after login

How to write python piecewise function?

How to write python piecewise function?

3. Draw a triangle waveform:

#!/usr/bin/python
# -*- coding:utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
def triangle_wave(x, c, c0, hc):
   x = x - int(x)  #三角波周期为1 因此只取小数部分进行计算
   if x < c0:
       return x / c0 * hc
   elif x >= c:
       return 0.0
   else:
       return (c-x)/(c-c0)*hc
x = np.linspace(0, 2, 1000)
y = np.array([triangle_wave(t, 0.6, 0.4, 1.0) for t in x])
plt.figure()
plt.plot(x, y)
plt.ylim(-0.2, 1.2)   #限制y的范围
plt.show()
Copy after login

How to write python piecewise function?

How to write python piecewise function?

Recommended tutorial: "python video tutorial"

The above is the detailed content of How to write python piecewise function?. 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!