【问题标题】:numpy noisy sin wave, with custom amplitude and frequencynumpy 嘈杂的正弦波,具有自定义幅度和频率
【发布时间】:2021-02-26 17:24:10
【问题描述】:

我在关注以下帖子:Produce random wavefunction

第一个答案接近我需要的,但我无法正确修改它。具体来说,我需要一个 100 的幅度,以及正在显示的 1000 的 5 个周期。

x = np.linspace(1, 1000)
y = 100*(np.sin(x) + np.random.normal(scale=0.1, size=len(x))

如上所示,我尝试将 y 乘以 100,这会改变幅度,但不会改变 100。我也不知道如何改变频率。

【问题讨论】:

  • np.sin 的角度以弧度为单位。正弦波的周期是 2 pi 弧度。 5 个周期是 5 * 2pi = 10 pi 弧度。

标签: python python-3.x numpy


【解决方案1】:

这就是你要找的吗?注意 2*pi (rad!):

import numpy as np
import matplotlib.pyplot as plt
import math

x = np.linspace(1, 1000)
#y = 100*(np.sin(x/5) + np.random.normal(scale=0.1, size=len(x))) # <- your solution
#y = 100*(np.sin(x/1000*2*math.pi)) # <- one full period
#y = 100*(np.sin(x/1000*2*math.pi*5)) # <- 5 full periods
y = 100*(np.sin(x/1000*2*math.pi*5) + np.random.normal(scale=0.1, size=len(x))) # <- 5 full periods + noise
plt.scatter(x, y)
plt.show()

导致

【讨论】:

  • 是的,输出就是我需要的!也可以使用 np.linespace 吗?说设置 x=1000
  • 当然,我在第 4 行中为 x 使用了 linspace。我可以对其进行参数化,但想明确一点。
【解决方案2】:

import numpy as np
from matplotlib.ticker import FuncFormatter, MultipleLocator
import matplotlib.pyplot as plt

x = np.linspace(0, 10 * np.pi, num=600)
n = np.random.normal(scale=8, size=x.size)
s = 100 * np.sin(x)
y = 100 * np.sin(x) + n

plt.Figure(figsize=(1, 1.5), dpi=80)
plt.plot(x, y, label='Total')
plt.plot(x, s, label='Sine')
plt.plot(x, n, label='Gaussian White Noise')
ax = plt.gca()

ax.xaxis.set_major_formatter(FuncFormatter(
    lambda val, pos: '{:.0f}$\pi$'.format(val / np.pi) if val != 0 else '0'
))
ax.xaxis.set_major_locator(MultipleLocator(base=np.pi))

plt.legend()
plt.savefig("noisey_sine.png", dpi=80)
plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-08
    • 2015-01-11
    • 2021-03-05
    • 1970-01-01
    • 2015-12-16
    • 2023-04-06
    • 1970-01-01
    • 2021-12-15
    相关资源
    最近更新 更多