对于阶乘(并行和普通),找不到相同的答案 [英] The answer is not found same for the factorial (Parallel and Normal)

查看:109
本文介绍了对于阶乘(并行和普通),找不到相同的答案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么下面的答案不一样?为什么下面的答案不一样?

常规编码:

Why is not The answer same following? Why is not The answer same following?

Normal coding :

for (long i = 1; i <= 5; i++)
 {
   sum = sum * i;
 }



并行编码:



Parallel Coding :

Parallel.For(1, 5, delegate(int i){ sum = sum * i; });


parallel = 24的结果
正常= 120的结果
为什么?


result of parallel=24
result of Normal=120
why ?

推荐答案

在并行for循环中,循环大小不包含在循环中,而在正常情况下,for循环中包含循环大小.请查看有关并行编程 [
In the parallel for loop the loop size is not inclusive to the loop where as in normal for loop the loop size included. Take look at for detail for Parallel Programming[^] MSDN article.




您尝试对一个迭代的结果取决于前一个迭代的计算进行并行化处理.如果在乘法中未使用总和,则该值将不会转移到下一个迭代中.
您只能使迭代彼此不相关的东西并行化.

这样做时,您的结果可能会在运行它的机器上有所不同,总和值需要关闭,以确保它不会在循环外生效.

希望这会有所帮助.

关于AT
Hi,

You have tried to parallize a calculation where the result of one iteration is dependent on the previous. If the sum was not used in the multiplication the value would not be transferred to the next iteration.
You can only parallize stuff where iterations have no relation to each other.

Your result may vary on the machine you run it on when you do it like this, the sum value needs closure th make sure it''s not effected outside the loop.

Hope this helps.

Regards, AT


原因是sum的值已从第一个for循环中更改,并在第二个代码块中再次使用.尝试使用2个不同的变量,例如:sum1sum2

问候,
爱德华
The reason is,,,, the value of sum was changed from the 1st for loop and used again in the second block of codes. Try using 2 different variables like: sum1 and sum2

Regards,
Eduard


这篇关于对于阶乘(并行和普通),找不到相同的答案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆