Will Calderwood Will Calderwood - 1 month ago 6
C# Question

Am I going crazy or is Math.Pow broken?

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.

Answer

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

Comments