Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math.Pow is not calculating correctly

Tags:

c#

pow

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

like image 441
Olivier_s_j Avatar asked Nov 28 '10 15:11

Olivier_s_j


People also ask

Is Math POW inefficient?

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.

What can I use instead of Math POW?

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.

Does Math POW return a double?

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.

Does Math pow need to be imported?

The pow() method is a part of java. lang. Math class, you need to import this class in your code to use the function.


2 Answers

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.

like image 107
Heinzi Avatar answered Oct 27 '22 15:10

Heinzi


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));
like image 22
Yuriy Faktorovich Avatar answered Oct 27 '22 15:10

Yuriy Faktorovich