如何在Ruby中生成平均值遵循正弦波的随机数?

Bry*_*yan 0 ruby random

我不是数学家,所以我真的不知道我想做的是什么,但是我敢肯定有个名字。;-)

我想在Ruby中生成一个随机数数组,该数组的每个元素的平均值遵循正弦波。我的意思是每个元素的平均值nary[0..n].inject(:+).to_f / (n + 1)。因此,如果我从0..n随机数数组中循环并像我描述的那样生成平均值,我希望结果值遵循正弦波。我只是不知道如何以这种方式实际生成随机数...

# assuming `ary` is the array of random numbers
# I'm trying to figure out how to generate...

averages = []

(0..ary.size).each do |n|
  averages << ary[0..n].inject(:+).to_f / (n + 1)
end

# `averages` should plot as a sine wave now...
Run Code Online (Sandbox Code Playgroud)

mae*_*ics 5

这是个主意。创建一个具有一定样本量的类,该类将在一个正弦波上生成多个点,并在该点之上或之下添加一些随机的“忽悠因子”(方差)。这样,如果在样本量中绘制点数,则应根据配置的方差(软糖因子)看到带有“粗糙度”的正弦波。

class RandomSineWave
  attr_reader :size
  def initialize(size=20, variance=0.2)
    @size = size
    @step = 2 * Math::PI / size
    @position = 0
    @variance = variance
  end
  def next
    @position = 0 if @position >= 2 * Math::PI
    next_rand = Math.sin(@position) + (rand * @variance) - (@variance / 2)
    @position += @step
    next_rand
  end
end

# Generate TSV output for demonstration.
rsw = RandomSineWave.new
rsw.size.times { |i| puts [i, rsw.next].join "\t" }
Run Code Online (Sandbox Code Playgroud)

随机正弦波图

您可以通过修改构造函数的第二个参数来摆弄“粗糙度”:

rsw = RandomSineWave.new(20, 0.8) # Results plotted below...
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

  • 顺便说一句,您用什么来获得这些漂亮的地块? (2认同)