I want to calculate Euler number with multiple threads using this formula =∑((3k) ^ 2 + 1)/(3k)! , k =0,... ,∞ , but I am not getting the right results so far and once of the problems is that when I use fairly big number I am going out of range for decimal for factorial function here is what I've done so far
static void Main(string[] args)
{
Console.WriteLine(Program.Calculate(5, 1));
}
public static decimal Calculate(int x, byte taskNumber)
{
var tasks = new List<Task<decimal>>();
for (int i = 0; i < x; i += (x / taskNumber))
{
int step = i;
tasks.Add(Task.Run(() =>
{
int right = (step + x / taskNumber) > x ? x : (step + x / taskNumber);
return ChunkE(step + 1, right);
}));
}
Task.WaitAll(tasks.ToArray());
return tasks.Select(t => t.Result).Aggregate(((i, next) => i + next));
}
then I have simple factorial and euler functions
public static decimal ChunkFactorial(int left, int right)
{
//Console.WriteLine("ChunkFactorial Thread ID :" + Thread.CurrentThread.ManagedThreadId);
if (left == right)
{
return left == 0 ? 1 : left;
}
else
{
return right * ChunkFactorial(left, right - 1);
}
}
public static decimal ChunkE(int left, int right)
{
if(left == right)
{
return left == 0 ? 1 : left;
}
else
{
return ((3 * right) * (3 * right) + 1) / ChunkFactorial(left, right) + ChunkE(left, right - 1);
}
}
What I want to achieve is calculating Euler number up until
x
precision using different amount of tasks.What I am getting with this call is 41.01666..7 if I increase
x
decimal will eventually overflow. How can I fix this problem I tried using BigInteger but then it begin to be mess and I loose precision of the result.. Any ideas?Also when I start the program with 1 task I get one result and when I start program with 4(or different of 1) I get different result I don't know what I am missing..