简体   繁体   English

MoreLinq 的 Scan 和 For 循环返回不同的结果

[英]MoreLinq's Scan and For Loop returns different results

I need to compute outputs from inputs using the formula:我需要使用以下公式计算inputsoutputs

Output(i) = inputs(i) * factor + outputs(i - 1) * (1 - factor)

I implemented this using a for loop and MoreLinq's Scan extension:我使用for循环和 MoreLinq 的Scan扩展实现了这一点:

Int32 p = 5;

Decimal factor = (Decimal) 2 / (p + 1);

List<Decimal?> inputs = Enumerable.Range(1, 40).Select(x => (Decimal?)x).ToList(); 

// Using Scan extension  

List<Decimal?> outputs1 = inputs.Scan((x, y) => x * factor + (y * (1 - factor)) ?? 0).ToList(); 

// Using for loop

List<Decimal?> outputs2 = new List<Decimal?> { inputs[0] };

for (int i = 1; i < inputs.Count(); i++) 
  outputs2.Add(inputs[i] * factor + (outputs2[i - 1] * (1 - factor)) ?? 0);

However, I get different outputs results.但是,我得到不同的输出结果。 What am I missing?我错过了什么?

Am I using Scan incorrectly?我是否错误地使用Scan

You are interpreting parameters of transformation function in the wrong order (check out the source code to see how transformation is invoked).您正在以错误的顺序解释transformation function 的参数(查看源代码以了解如何调用transformation )。 Change your code to:将您的代码更改为:

inputs.Scan((x, y) => y * factor + x * (1 - factor) ?? 0).ToList()

x is aggregator, ie previous value, y is the current one. x是聚合器,即先前的值,y 是当前值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM