Rila Nera
Rila Nera

Reputation: 49

Large double mathematical multiplication in C#

I want to multiply this number:

5374711027510012111075768211110475111691021051041057653548210911210211112250867 66690120741165250567278571217510410482757487

with this number:

4956889911565576581818287977011111065876967103548749122901151091038910610511189

But when I cast the result to string I get this:

2.66418508698446E+201

Which is:

266418508698446000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000

Not exactly the precise number, those zeros represent loss of precision, am I right?

Is it possible to get the precise number (every single digit) out of this calculation using C#?

Thanks

Upvotes: 0

Views: 2104

Answers (3)

Hunter
Hunter

Reputation: 2470

If you are using .NET 4.5, make use of system.Numerics assembly. http://msdn.microsoft.com/en-us/library/system.numerics.aspx

var num1 = BigInteger.Parse("5374711027510012111075768211110475111" + "69102105104105765354821091121021111225086766690120741165250567278571217510410482757487");

var num2 = BigInteger.Parse("4956889911565576581818287977011111065876967103548749122901151091038910610511189");

Console.WriteLine(num1 + num2);

Upvotes: 0

jason
jason

Reputation: 241641

Yes. Use BigInteger. It's designed for this purpose. The numbers you are using won't fit in the primitive integral and can't even be represented precisely in the floating-point types1.

BigInteger m = BigInteger.Parse("374711027510012111075768211110475111691021051041057653548210911210211112250867 66690120741165250567278571217510410482757487");
BigInteger n = BigInteger.Parse("4956889911565576581818287977011111065876967103548749122901151091038910610511189");
var product = m * n;
Console.WriteLine(proudct);

1: Single-precision floating point can represent all integers between -2^24 and 2^24 exactly because it has a 23-bit explicit plus one implicit bit mantissa; after that it loses precision. As

2^24 = (2^10)^2.4 ~ (10^3)^2.4 ~ 10^7

we lose precision for some integers after approximately seven digits.

Similarly, double-precision floating point can represent all integers between -2^53 and 2^53 exactly because it has a 52-bit explicit plus one implicit bit mantissa; after that it loses precision. As

2^53 = (2^10)^5.3 ~ (10^3)^5.3 ~ 10^16

we lose precision for some integers after approximately sixteen digits.

Upvotes: 11

Sebastian Negraszus
Sebastian Negraszus

Reputation: 12215

A double has a limited maximum precision (number of significant digits) of 15. Your numbers have too many digits and thus cannot be stored as double without loss of precision.

Upvotes: 0

Related Questions