I think you are on the right track, noise is additive in nature and if you look at the (SNR) Signal to Noise Ratio calculation
SNR = 20 * log(p_s)/(p_n)
which is nothing but
SNR = 20 (log(p_s) - log(p_n))
so we are basically subtracting the power of noise from the signal(which has noise)
I would do the same as what you have posted
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(137)
t = np.linspace(0, 10, 100)
p = np.sin(t)
percentage = 0.05
n = np.random.normal(0, p.std(), t.size) * percentage
pn = p + n
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax1.set_title('Noise added to entire signal')
ax1.plot(t, p, label='pure signal')
ax1.plot(t, pn, label='signal+noise')
ax2 = fig.add_subplot(212)
ax2.plot(t, pn - p, label='added noise', c='r')
plt.legend()
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax1.set_title('Noise added to part of the signal')
ax1.plot(t, p, label='pure signal')
random_indices = np.random.randint(0, t.size, int(t.size*percentage))
pr = p.copy()
pr[random_indices] += n[random_indices]
ax1.plot(t, pr, label='signal+noise')
ax2 = fig.add_subplot(212)
ax2.plot(t, pr - p, label='added noise', c='r')
plt.legend()
plt.show()
One interesting thing that I have noticed is np.random.normal
for very small values of variance mainly samples positive values, so it is better to scale the 5% ie, the variance after sampling with a higher variance value
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.