Math.Pow is not calculating correctly

后端 未结 6 1282
萌比男神i
萌比男神i 2020-12-01 18:52

I\'m having a problem with C#. To be precise with the Math.pow(). If I try to calculate 15^14 then I get \"29192926025390624\". But if I calculate it with Wolfram Alpha I ge

6条回答
  •  悲哀的现实
    2020-12-01 19:29

    Math.Pow works on doubles. Doubles are 64 bit floating point and have about 15-16 digits of precision in C#, and therefore, what you are seeing is a rounding error. That is how floating point numbers work.

    If you need more precision, try to use decimal. It is 128 bits and uses 10 as the base. This gives you accurate representation of numbers up to 28-29 significant digits. You can easily define your own Pow method for decimal.

    If decimal is not enough, turn to BigInteger, which was added in .NET 4.

提交回复
热议问题