本文介绍了RX:状态变换顺序,例如指数移动平均线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你怎么能在RX做一个简单的,有状态变换序列的?



说,我们要做出的IObservable noisySequence的指数移动平均变换。



每当noisySequence蜱,emaSequence应剔和返回值
(previousEmaSequenceValue *(1-拉姆达)+ latestNoisySequenceValue *波长)



我想我们使用的主题,但究竟怎么了?

 公共静态无效的主要()
{

变种兰特=新的随机();

的IObservable<双>序列观测=
.Interval(TimeSpan.FromMilliseconds(1000))
。选择(价值=>价值+ rand.NextDouble());

Func键<双层,双> addNoise = X => X + 10 *(rand.NextDouble() - 0.5);

的IObservable<双> noisySequence = sequence.Select(addNoise);

受试对象;双> exponentialMovingAverage =新的受试对象;双>(); //?


sequence.Subscribe(价值=> Console.WriteLine(原序+值));
noisySequence.Subscribe(价值=> Console.WriteLine(噪声序列+值));
exponentialMovingAverage.Subscribe(价值=> Console.WriteLine(EMA序+值));

到Console.ReadLine();
}


解决方案

这是你可以附加状态的序列。在这种情况下,计算出的最后10个值的平均值

  VAR movingAvg = noisySequence.Scan(新名单<双>( ),
(缓冲,值)=>
{
buffer.Add(价值);
如果(buffer.Count> MAXSIZE)
{
buffer.RemoveAt(0);
}
返回缓冲区;
})选择(缓冲=> buffer.Average());



但是,你可以使用窗口(其中缓冲区是有点泛化的),让你的平均了。

  noisySequence.Window(10)
。选择(窗口=> window.Average())
.SelectMany(averageSequence => averageSequence);


How can you do in RX a simple, stateful transform of a sequence?

Say we want to make an exponential moving average transform of a IObservable noisySequence.

Whenever noisySequence ticks, emaSequence should tick and return the value(previousEmaSequenceValue*(1-lambda) + latestNoisySequenceValue*lambda)

I guess we use Subjects, but how exactly?

    public static void Main()
    {

        var rand = new Random();

        IObservable<double> sequence  = Observable
            .Interval(TimeSpan.FromMilliseconds(1000))
            .Select(value => value + rand.NextDouble());

        Func<double, double> addNoise = x => x + 10*(rand.NextDouble() - 0.5);

        IObservable<double> noisySequence = sequence.Select(addNoise);

        Subject<double> exponentialMovingAverage = new Subject<double>(); // ??? 


        sequence.Subscribe(value => Console.WriteLine("original sequence "+value));
        noisySequence.Subscribe(value => Console.WriteLine("noisy sequence " + value));
        exponentialMovingAverage.Subscribe(value => Console.WriteLine("ema sequence " + value));

        Console.ReadLine();
    }
解决方案

This is how you can attach state to a sequence. In this case it calculates the average of the last 10 values.

var movingAvg = noisySequence.Scan(new List<double>(),
(buffer, value)=>
{
    buffer.Add(value);
    if(buffer.Count>MaxSize)
    {
        buffer.RemoveAt(0);
    }
    return buffer;
}).Select(buffer=>buffer.Average());

But you could use Window (which Buffer is sort of a generalisation of) to get your average too.

noisySequence.Window(10)
   .Select(window=>window.Average())
   .SelectMany(averageSequence=>averageSequence);

这篇关于RX:状态变换顺序,例如指数移动平均线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 04:15