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
Math. pow is slow because it deals with an equation in the generic sense, using fractional powers to raise it to the given power. It's the lookup it has to go through when computing that takes more time. Simply multiplying numbers together is often faster, since native calls in Java are much more efficient.
Introduced in ES2016, the infix exponentiation operator ** is an alternative for the standard Math. pow function. Infix notation is considered to be more readable and thus more preferable than the function notation.
pow() is used to return the value of first argument raised to the power of the second argument. The return type of pow() method is double.
The pow() method is a part of java. lang. Math class, you need to import this class in your code to use the function.
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.
Math.Pow works on doubles. This implementation with long gets the correct answer:
Func<long, int, long> power = null;
power = (i, p) => p == 1 ? i : i*power(i, p - 1);
Console.WriteLine(power(15, 14));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With