python分段函数如何编写

 时间:2024-10-11 19:01:03

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 1elif x < 0:return -1else: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()

python分段函数如何编写

2、使用Matplotlib绘制分段函数:代码:#!/usr/bin/python# -*- coding:utf-8 -*-import numpy as npimport matplotlib.pyplot as pltdef sgn(value):if value < 4:return 20else: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()

python分段函数如何编写

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分段函数如何编写
  • 如何用蒙特卡洛方法在Python环境下计算圆周率
  • Python编程:怎么计算100到200的所有素数
  • Python编程:怎么判断用户输入的年份是否为闰年
  • python如何判断奇偶数?
  • python字符串逆序输出
  • 热门搜索
    身份证过期了怎么补办 威狮轮胎质量怎么样 江苏高考总分480怎么算的 我的世界黄金怎么挖 总是打哈欠是怎么回事 怎么写信 怎么折青蛙 眼睛浮肿怎么办 铅笔英语怎么读 预产期怎么计算