微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

仅使用 numpy,有没有办法创建方波?

如何解决仅使用 numpy,有没有办法创建方波?

我尝试过使用掩码并制作像 x = [0,0.5,0.51,1,1.01],y = [1,-1,1] 这样的列表当然有效,但很乏味而且不就像我想从 x = 0 到 5 制作方波一样好。

解决方法

你可以写一个这样的小函数来填充 x 和 y


import matplotlib.pyplot as plt
import math

def SquareWave(high,low,start,end,width):
    print("Square Wave")
    ##Calculate how many cycles
    ncycles = int(math.ceil((end - start)/width)) #Round up
    print(ncycles)
    x=[]
    y=[]
    x.append(start)
    y.append(high)
    xstep = width / 2 
    for n in range(ncycles):
        start += xstep #Increment by the step width
        x.append(start)
        y.append(high)
        x.append(start)
        y.append(low)
        start += xstep #Increment by the step width
        x.append(start)
        y.append(low)
        x.append(start)
        y.append(high)
    return(x,y)
        
        

x,y = SquareWave(1,-1,5,1)

plt.plot(x,y)

Output

,

:一般解决方案:

import matplotlib.pyplot as plot 
import numpy as np 

def sq(x,y):
    
    mindiff = min([x[i+1]-x[i] for i in range(4)])
    up_x = np.arange(x[0],x[-1],mindiff)
    up_y = list(map(lambda i: y[sum(i > x)],up_x))
    print(up_y)
    plot.plot(up_x,up_y)
    plot.show()

x = [0,0.5,0.51,1,1.01]
y = [1,1] 
sq(x,y)


:特定于您的代码:

import matplotlib.pyplot as plot 
import numpy as np 
  
up_t = list(np.linspace(x[0],x[1],100)) + list([0.5])+list([0.51])+list(np.linspace(x[2],x[3],100)) + list([1.01])
up_y = [1 for i in range(100)] + [1,-1]+ [-1 for i in range(100)] + [1]

t = np.array(up_t)
plot.plot(up_t,up_y)
plot.show()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。