Generate periodic square and triangle waves using python



Python
library
pip

MeCab

Common
class

pickle

read/readline

numpy
asfarray

digitize

expit

linalg.solve

meshgrid

mgrid

ndmin

pad

poly1d

polyfit

prod

shape

matplotlib
figure

pcolormesh

scatter

pytorch
BCELoss, MSELoss

device

Embedding

TensorDataset, Dataloader

RNN, LSTM
scikit-learn
SVC

GaussianNB

scipy
interpolate
tkinter
postscript

image display

frame, grid

Crop Image

other
linear interpolation

Hysteresis switch

Square/Triangle wave

OpenAI gym
CartPole-v0

By purpose
1 of K Coding


Release date:2025/3/19         

In English


Explains how to generate a periodic square wave in python. The functions used are scipy's signal.square, sawtooth.

■Square wave

import numpy as np
from scipy import signal
import matplotlib.pyplot as plt

f = 5 # Frequency [Hz]
x = np.arange(0,1,0.001)
y = signal.square(2 * np.pi * f * x)

plt.plot(x, y)
plt.show()


The results are as follows.


■Triangle wave

import numpy as np
from scipy import signal
import matplotlib.pyplot as plt

f = 5 # Frequency [Hz]
x = np.arange(0,1,0.001)
y = signal.sawtooth(2 * np.pi * f * x, 0.5)

plt.plot(x, y)
plt.show()


The results are as follows.











List of related articles



Python
library
pip

MeCab

Common
class

pickle

read/readline

numpy
asfarray

digitize

expit

linalg.solve

meshgrid

mgrid

ndmin

pad

poly1d

polyfit

prod

shape

matplotlib
figure

pcolormesh

scatter

pytorch
BCELoss, MSELoss

device

Embedding

TensorDataset, Dataloader

RNN, LSTM
scikit-learn
SVC

GaussianNB

scipy
interpolate
tkinter
postscript

image display

frame, grid

Crop Image

other
linear interpolation

Hysteresis switch

Square/Triangle wave

OpenAI gym
CartPole-v0

By purpose
1 of K Coding