Click here to Skip to main content
15,900,258 members
Please Sign up or sign in to vote.
2.00/5 (2 votes)
See more:
As you know computer doesn't show all of digits of a large number.
For example it show "1.07150860718627E+301" as result of:
C#
Math.Pow(2, 1000);

How can I have got normal mode result?
Posted
Updated 10-Sep-12 10:43am
v2

The problem is that is being computed in type double, which is only 64-bits. double is a "floating-point" representation and stores numbers as the most significant 53 bits of the number and a 10 bit "scale". This is why only about 15 decimal digits of prcision are possible.
If you really need all of the precision for a very large integer, use the BigInteger data type.
 
Share this answer
 
Comments
[no name] 10-Sep-12 15:26pm    
Thank you.
It was really helpful.
Sergey Alexandrovich Kryukov 11-Sep-12 15:18pm    
No, the problem is that this is a floating point, which might be the inadequate way of presenting of the integer power of integer value, when it comes to absolute precision.
The type which copes with this is System.Numerics.BigInteger -- please see my answer.
--SA
Matt T Heffron 11-Sep-12 17:29pm    
That's basically what I said in my solution. I just presented that double is only 64 bits to start the OP thinking about how 2^1000 could not possibly fit in 64 bits.
(I'm still wondering how the OP didn't know this given his stated education and experience. It is usually covered *very* early in programming education.)
The root problem is that the floating-point types are designed for approximate calculations. This is unavoidable in principle. Did you know that in general case, the single real number contains the infinite volume of information? So, there is no a way in principle to present such value without approximation.

Now, your case deals with integer values. For integer values, there is a wonderful type with unlimited size: System.Numerics.BigInteger:
http://msdn.microsoft.com/en-us/library/system.numerics.biginteger.aspx[^].

"Unlimited" actually means "limited by all available memory provided by the system to your application". And this is, well, a lot…

[EDIT]

By the way, this type is available to you as you use v.4.0. Good for you. Those who does not have development tools supporting this version could pick up the source code from Mono.

Good luck,
—SA
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900