我是靠谱客的博主 不安白云,这篇文章主要介绍python分段函数如何编写?,现在分享给大家,希望可以做个参考。

python分段函数如何编写?

python编写分段函数的方法:

1.绘制分段函数:y=4sin(4πt)-sgn(t-0.3)-sgn(0.72-t)

代码:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/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()
登录后复制

662f89dd2589ebdf83b68bef2e39eaa.png

51b2feb05988a2cf457839a1c0cf03f.png

2.使用Matplotlib绘制分段函数:

代码:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/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, 'b', label='type') plt.legend() plt.show()
登录后复制

1f10ee4c5580a0a217577684be9989d.png

859b6ff1e0a48b533aff3088a8a9e9b.png

3.绘制三角波形:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#!/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()
登录后复制

906e57be365c8bf6efb2e48d69ffe4b.png

e0847551fa686f602d3a150aa8681b9.png

推荐教程:《python视频教程》

以上就是python分段函数如何编写?的详细内容,更多请关注靠谱客其它相关文章!

最后

以上就是不安白云最近收集整理的关于python分段函数如何编写?的全部内容,更多相关python分段函数如何编写内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(107)

评论列表共有 0 条评论

立即
投稿
返回
顶部