python分段函数如何编写?


当前第2页 返回上一页

代码:

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文件操作之合并文本文件内容方法介绍

Python语言怎么样?

Python中的字典排序如何实现代码说明

Python如何处理表格?

Python中的条件判断语句基础学习

Python怎么导入模块

学习Python能做什么

Python怎么输出分数形式

Python适合游戏开发吗

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...