Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiplying BigInteger by Double

My Physics teacher gave the class a hard task. I'm trying to create a program that will calculate some things for me. At a certain point I need to multiply an amount of molecules by a percentage. Ulong can't hold numbers as large as 6022 * 10 ^ 19, so I have to use BigInteger from .net 4.0. However multiplication cannot be applied to BigInteger and double. I only need the whole number. Is there any way to bypass this? The code is as follows:

private static BigInteger pencapmoles = BigInteger.Pow(6022/9, 19);
private static BigInteger inkmoles = pencapmoles;
private static BigInteger tries = 0;
private static BigInteger molesinbucket = BigInteger.Pow(26761768, 19);
private static double percentage;
static void Main(string[] args)
{
    while (inkmoles > 1) 
    {
        percentage = (double)(inkmoles / molesinbucket);
        inkmoles = pencapmoles * percentage;
        tries++;
    }
    Console.WriteLine($"It only took us {tries} tries.");
}

1 Answers

You would be better off switching all computations either to double or to BigInteger. C# double has enough range to hold values a lot greater than 1019, but the answer is going to have a slight imprecision. It is a near certainty that it is going to be enough for the purposes of solvind your task.

If you switch to BigInteger, multiply first, and then do the division:

inkmoles = (inkmoles * pencapmoles) / molesinbucket;
like image 104
Sergey Kalinichenko Avatar answered Aug 04 '26 05:08

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!