Harshvardhan Uppaluru
Harshvardhan Uppaluru

Reputation: 49

math equations for a triangular wave

I have been unsuccessfully trying to plot functions which look even remotely similar to the image below in numpy, python, matplotlib. Is there any f(x)= .... for this image or similar plots?

enter image description here

Upvotes: 0

Views: 703

Answers (2)

JohanC
JohanC

Reputation: 80509

Taking the fractional part of x creates a saw-tooth-like curve. Then subtracting half of it and taking the absolute value makes the saw tooth go both ways,

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 10, 1000)
y = np.where((x > 2.75) & (x < 7.75), np.abs(x - np.floor(x) - 0.5) + 0.75, 1)

plt.plot(x, y, color='navy')
plt.ylim(0, 2)
plt.xlim(0, 10)

resulting plot

PS: For x-values between 0 and 1, an example could be:

x = np.linspace(0, 1, 1000)
y = np.where((x > 0.275) & (x < 0.775), np.abs(x*10 - np.floor(x*10) - 0.5) + 0.75, 1)

plt.plot(x, y, color='navy')
plt.ylim(0, 2)
plt.xlim(0, 1)

Upvotes: 4

Mr. T
Mr. T

Reputation: 12410

import numpy as np
from matplotlib import pyplot as plt

x = np.linspace(-10, 10, 1000)
y = np.arccos(np.cos(x))

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

enter image description here

Upvotes: 1

Related Questions