python分段函数如何编写?
python分段函数如何编写?
python编写分段函数的方法:
1.绘制分段函数:y=4sin(4πt)-sgn(t-0.3)-sgn(0.72-t)
代码:
立即学习“Python免费学习笔记(深入)”;
#!/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 <p><img src="https://img.php.cn/upload/image/192/999/624/1592543103147273.png" title="1592543103147273.png" alt="662f89dd2589ebdf83b68bef2e39eaa.png"></p><p><img src="https://img.php.cn/upload/image/453/118/842/1592543108798534.png" title="1592543108798534.png" alt="51b2feb05988a2cf457839a1c0cf03f.png"></p><p>2.使用Matplotlib绘制分段函数:</p><p>代码:</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/00968c3c2c15" style="max-width:90%" rel="nofollow" target="_blank">Python免费学习笔记(深入)</a>”;</p><pre class="brush:php;toolbar:false">#!/usr/bin/python# -*- coding:utf-8 -*-import numpy as npimport matplotlib.pyplot as pltdef sgn(value): if value <p><img src="https://img.php.cn/upload/image/313/239/177/1592543114924994.png" title="1592543114924994.png" alt="1f10ee4c5580a0a217577684be9989d.png"></p><p><img src="https://img.php.cn/upload/image/255/421/734/1592543121587503.png" title="1592543121587503.png" alt="859b6ff1e0a48b533aff3088a8a9e9b.png"></p><p>3.绘制三角波形:</p><pre class="brush:php;toolbar:false">#!/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 = 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视频教程》