Am I going crazy or is Math.Pow broken?

空扰寡人 提交于 2019-12-10 17:48:44

问题


I used the base converter from here and changed it to work with ulong values, but when converting large numbers, specifically numbers higher than 16677181699666568 it was returning incorrect values. I started looking into this and discovered that Math.Pow(3, 34) returns the value 16677181699666568, when actually 3^34 is 16677181699666569. This therefore throws a spanner in the works for me. I assume this is just an issue with double precision within the Pow method? Is my easiest fix just to create my own Pow that takes ulong values?

If so, what's the quickest way to do Pow? I assume there's something faster than a for loop with multiplication each time.


回答1:


You can use BigInteger.Pow. Or use my power method for long.




回答2:


The problem is that Math.Pow returns a double, and the closest double value to 16677181699666569 is 16677181699666568.

So without getting Math.Pow involved:

long accurate = 16677181699666569;
double closestDouble = accurate;
// See http://pobox.com/~skeet/csharp/DoubleConverter.cs
Console.WriteLine(DoubleConverter.ToExactString(closestDouble));

That prints 16677181699666568.

In other words whatever Math.Pow does internally, it can't return a result that's more accurate than the one you're getting.

As others have said, BigInteger.Pow is your friend if you're using .NET 4.




回答3:


Read What Every Computer Scientist Should Know About Floating-Point

Floating point types are an approximation, the rounding you see is normal.

If you want exact results use BigInteger.




回答4:


I assume this is just an issue with double precision within the Pow method?

Yes.

Is my easiest fix just to create my own Pow that takes ulong values?

You can use BigInteger.Pow.




回答5:


If you're using .NET Framework 4, Microsoft has included a new BigInteger class that lets you manipulate large numbers.

http://msdn.microsoft.com/en-us/library/system.numerics.biginteger.aspx

Alternatively, you can use a nice library that someone else created:

http://intx.codeplex.com/ (IntX library)



来源:https://stackoverflow.com/questions/5407298/am-i-going-crazy-or-is-math-pow-broken

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!