Multiplying BigInteger by Double

风流意气都作罢 提交于 2019-12-11 01:40:39

问题


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:


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;


来源:https://stackoverflow.com/questions/46506473/multiplying-biginteger-by-double

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!