Math error width 'Decimal' type of variables or something else ?
Hello ,
I have made simple program for calculating square root of numbers
at 28 decimal places, that contains this function :
decimal CalculateSquareRoot(decimal number)
{
decimal result;
decimal square;
decimal c;
string end;
square = number * 0.5M;
c = FindC(square);
result = square * square;
end = ResultControl(result,number,c);
while(end != "end")
{
while(end == "bigger" && c<=square)
{
square = square - c;
result = square * square;
end = ResultControl(result,number,c);
}
c = c / 10;
while(end == "smaller")
{
square = square + c;
result = square * square;
end = ResultControl(result,number,c);
}
c = c / 10;
}
return square;
}
Algorithm is ok but I have found problem,
program do not calculate correct,
simple math operation such as subtraction
In the line 21 ( problematic line ) of program code :
square = square - c;
for values :
square = 11111111,061111080443055417550
c = 0,0000000000000000000001
square = 11111111,061111080443055417550 ? incorrect
This is incorrect, and as it can be seen it seems that
calculation is not done at all because the result of
calculation is the same as one of the addends.
This should be new value of 'square' variable afther subtraction operation
square = 11111111,0611110804430554175499
Since this calculation is inside the 'while' loop
program becomes unresponsive because of this error.
All variables are type of 'Decimal'
and this math operation should go without errors
since this type can accept numbers up to 28 decimals.
Also this same function works perfectly inside program where
variables are declared as type of 'BigInteger',
and that version of program can calculate square root of numbers
at wanted number of decimal places restricted only by quantity of memory.
I can't find pattern for this error and this example is not isolated case.
If someone had similar problem please answer how to solve it.
Program is written in IDE SharpDevelop ver 4.2.2, C#.
All the best,
Perić Željko