d49272f610f2da8544e14c054be28885.png

python分段函数如何编写?

python编写分段函数的方法:

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

代码:#!/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()

d1af15e9a22b0cd37a09d6be5acc1b1f.png

454dd3cff5a9f875e2c80259f3492810.png

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

代码:#!/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()

e87d67c49144b9956b610dba984ba3ab.png

e4ec02352abfe2b6bcb0a8f41572dc77.png

3.绘制三角波形:#!/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()

0b159526d34416f6d1b53666acf5d16c.png

1900432ec97190d0ebe1b0b9b1e15e90.png

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐