python分段函数编写程序_python分段函数如何编写?

本文详细介绍了如何在Python中编写分段函数,包括使用numpy和matplotlib库绘制分段函数y=4sin(4πt)-sgn(t-0.3)-sgn(0.72-t),以及利用Matplotlib实现三角波形和符号函数。通过实例展示如何创建并理解这些复杂的函数图形。
摘要由CSDN通过智能技术生成

python分段函数如何编写?

python编写分段函数的方法:

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

代码:

#!/usr/bin/python# -*- coding:utf-8 -*-import numpy as npimport 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 0t = 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()

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

代码:

#!/usr/bin/python# -*- coding:utf-8 -*-import numpy as npimport matplotlib.pyplot as pltdef sgn(value): if value < 4: return 20 else: return 15plt.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()

3.绘制三角波形:

#!/usr/bin/python# -*- coding:utf-8 -*-import numpy as npimport matplotlib.pyplot as pltdef 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)*hcx = 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()

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值