I am writing a class which needs accurate division of the BigInteger class in C#.
Example:
BigInteger x = BigInteger.Parse("1000000000000000000000000000000000000000000000000000000000000000000000000000000000000");
BigInteger y = BigInteger.Parse("2000000000000000000000000000000000000000000000000000000000000000000000000000000000000");
x /= y;
Console.WriteLine(x.ToString());
//Output = 0
The problem is that being an Integer, naturally it does not hold decimal values. How can I overcome this to get the real result of 0.5 (given example).
P.S. The solution must be able to accurately divide any BigInteger, not just the example!
divide(BigInteger val) is used to calculate the division of two BigIntegers. BigInteger class internally uses array of integers for processing, the operation on object of BigIntegers are not as fast as on primitives.
The BIGINT data type is a machine-independent method for representing numbers in the range of -2 63-1 to 2 63-1. ESQL/C provides routines that facilitate the conversion from the BIGINT data type to other data types in the C language. The BIGINT data type is internally represented with the ifx_int8_t structure.
Initialize the large number along with a divisor. Iterate over the given number until we extract the part that is greater than the divisor. Now, iterate from where we left in the previous step until the end of the number. Divide the extracted part with a divisor and add it to the result.
What accuracy you need for the division? One way would be:
double
and divide by 1000The same in code:
BigInteger x = BigInteger.Parse("1000000000000000000000000000000000000000000000000000000000000000000000000000000000000");
BigInteger y = BigInteger.Parse("2000000000000000000000000000000000000000000000000000000000000000000000000000000000000");
x *= 1000;
x /= y;
double result = (double)x;
result /= 1000;
Console.WriteLine(result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With