Plinq 给出了与 Linq 不同的结果 - 我做错了什么?
谁能告诉我正确的 Plinq 代码是什么? 我将双精度数组的每个元素的正弦绝对值的平方根相加,但 Plinq 给出了错误的结果。
该程序的输出为:
Linq 聚合 = 75.8310477905274 (正确) Plinqaggregate = 38.0263653589291(大约是应该的一半)
我一定做错了什么,但我无法弄清楚是什么......
(我在 Core 2 Duo Windows 7 x64 PC 上使用 Visual Studio 2008 运行这个。 )
这是代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
double[] array = new double[100];
for (int i = 0; i < array.Length; ++i)
{
array[i] = i;
}
double sum1 = array.Aggregate((total, current) => total + Math.Sqrt(Math.Abs(Math.Sin(current))));
Console.WriteLine("Linq aggregate = " + sum1);
IParallelEnumerable<double> parray = array.AsParallel<double>();
double sum2 = parray.Aggregate((total, current) => total + Math.Sqrt(Math.Abs(Math.Sin(current))));
Console.WriteLine("Plinq aggregate = " + sum2);
}
}
}
Can anyone tell me what the correct Plinq code is for this? I'm adding up the square root of the absolute value of the sine of each element fo a double array, but the Plinq is giving me the wrong result.
Output from this program is:
Linq aggregate = 75.8310477905274 (correct)
Plinq aggregate = 38.0263653589291 (about half what it should be)
I must be doing something wrong, but I can't work out what...
(I'm running this with Visual Studio 2008 on a Core 2 Duo Windows 7 x64 PC.)
Here's the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
double[] array = new double[100];
for (int i = 0; i < array.Length; ++i)
{
array[i] = i;
}
double sum1 = array.Aggregate((total, current) => total + Math.Sqrt(Math.Abs(Math.Sin(current))));
Console.WriteLine("Linq aggregate = " + sum1);
IParallelEnumerable<double> parray = array.AsParallel<double>();
double sum2 = parray.Aggregate((total, current) => total + Math.Sqrt(Math.Abs(Math.Sin(current))));
Console.WriteLine("Plinq aggregate = " + sum2);
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
PLINQ 中聚合的工作方式略有不同。
来自 MSDN 博客:
因此,在您的情况下,您还需要传递一个累加器函数,该函数对并行聚合的输出求和(因此您看到的结果大约是应有结果的一半)。
Aggregate works slightly differently in PLINQ.
From MSDN Blogs:
So, in your case, you would also need to pass an accumulator function which sums the outputs of the paralleled aggregates (hence why you're seeing a result that is roughly half of what it should be).
谢谢 MSDN 博客。 现在看来工作正常。 我改变了我的代码如下:
Thank you MSDN Blogs. It now seems to be working correctly. I changed my code as follows: