10

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 get "29192926025390625". As you can see this only difference is 1 number. Wolfram Alpha is correct though. Why isn't C# ? and how do I fix this so I can get the correct value in C# ?7

My code is fairly simple since I'm just trying with hardcoded examples. So what I'm doing is : Math.Pow(15,14); This gives 29192926025390624. And not "29192926025390625" which is the correct answer.

Links : Wolfram Alpha

4

6 回答 6

11

Math.Pow operates on floating-point types, which are by definition inaccurate. If you need arbitrary precision integers, use an arbitrary precision integer type such as the BigInteger structure. BigInteger also has a Pow method.

于 2010-11-28T15:27:04.450 回答
5

Math.Pow适用于双打。这个 long 的实现得到了正确的答案:

Func<long, int, long> power = null;
power = (i, p) => p == 1 ? i : i*power(i, p - 1);
Console.WriteLine(power(15, 14));
于 2010-11-28T15:31:04.670 回答
4

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.

于 2010-11-28T15:27:55.913 回答
1

C# 的 Math.pow 返回一个 Double,一个 IEEE 754 标准浮点数。它只有 15 位有效数字:

http://msdn.microsoft.com/en-us/library/system.math.pow.aspx http://math.byu.edu/~schow/work/IEEEFloatingPoint.htm

于 2010-11-28T15:30:37.633 回答
1

Math.Pow() 工作正常,其双数据类型的问题 见此。

        double i = 29192926025390625;
        Console.WriteLine("{0}",i);//the result will be 29192926025390624.0

糟糕,抱歉,通过断点检查值;在你的程序中;

于 2010-11-28T15:48:56.700 回答
-1

每个计算机科学家都应该知道的关于浮点运算的知识

于 2010-11-28T15:32:57.867 回答