产生随机波函数 [英] Produce random wavefunction
问题描述
我需要在matplotlib中生成一条随机曲线.
例如,我的x值是从1到1000.我不想生成分散的随机 y 值,我需要一条平滑的曲线.就像某种幅度和波长变化的非常扭曲的正弦曲线.
是否已经存在可以让我轻松进行此操作的东西?
试试这个代码:
导入 matplotlib.pyplot 为 pl将numpy导入为npx = np.linspace(1, 10)定义 f(x):返回 np.sin(x) + np.random.normal(scale=0.1, size=len(x))pl.plot(x,f(x))
它会给你一个带有一些噪音的正弦波:
您正在寻找某种):
def runningMean(x, N):返回 np.convolve(x, np.ones((N,))/N)[(N-1):]pl.plot(x, runningMean(f(x), 10))
您使用的窗口( N
参数)越大,结果越平滑.
示例:
I need to produce a random curve in matplotlib.
My x values are from say 1 to 1000 for example. I don't want to generate scattered random y values, I need a smooth curve. Like some kind of very distorted sin curve with varying amplitude and wavelength.
Does something already exist to allow me to easily do this?
Try this code:
import matplotlib.pyplot as pl
import numpy as np
x = np.linspace(1, 10)
def f(x):
return np.sin(x) + np.random.normal(scale=0.1, size=len(x))
pl.plot(x, f(x))
It will give you a sin wave with some noise added to it:
Edit:
It seems like some kind of random walk is what you're looking for. This function will do that for you:
def f(x):
y = 0
result = []
for _ in x:
result.append(y)
y += np.random.normal(scale=1)
return np.array(result)
This is an example of what it can look like (with x = np.linspace(0, 1000, 1000)
):
It's not a function of x
any longer though, so the code should probably be refactored to generate a random walk with n
steps instead. I'll leave that to you :)
Edit 2:
If you want a smoother curve, you can apply a running mean (stolen from this question):
def runningMean(x, N):
return np.convolve(x, np.ones((N,))/N)[(N-1):]
pl.plot(x, runningMean(f(x), 10))
The bigger window (the N
parameter) you use, the smoother the result.
Example:
这篇关于产生随机波函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!