Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
853 views
in Technique[技术] by (71.8m points)

.net - BigInteger division in C#

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In the above example, the numbers are still small enough to be converted to double, so in this case you can say

double result = (double)x / (double)y;

If x and y are too huge for a double but still comparable, maybe this great trick is helpful:

double result = Math.Exp(BigInteger.Log(x) - BigInteger.Log(y));

But in general, when the BigInteger are huge, and their quotient is huge too, this is hard to do without importing a third-party library.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...