Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong Math.Pow() implementation for NaN number in .NET

Tags:

c#

.net

math

Why the Math.Pow(1.0, double.NaN) command returns NaN instead of the correct 1.0? I understand NaN as an indefinite value (mathematically) that represents all the real numbers including positive and negative infinities. And for all these values, the expression is always mathematically correct and equals 1.0.

E.g. Python has it, and 1**float("nan") == 1 is True, in accordance with IEEE standard:

For any value of y (including NaN), if x is +1, 1.0 shall be returned.

like image 922
BigFOX I Avatar asked Aug 27 '18 10:08

BigFOX I


People also ask

What does Math pow() do?

The Math. pow() function returns the base to the exponent power, as in base exponent , the base and the exponent are in decimal numeral system.

What does Math Pow do in C#?

The Math. Pow() method in C# is used to compute a number raised to the power of some other number.

How to write power function in javascript?

The Math. pow() method returns the value of x to the power of y (xy).


2 Answers

Any operation using a NaN returns NaN therefore Math.Pow(1.0, double.Nan) will return NaN. This is expected behaviour when using NaN in C#.

a method call with a NaN value or an operation on a NaN value returns NaN

See Here

Just because one language behaves in a certain way doesn't necessarily mean another language will behave that way

EDIT: for future reference Math.Pow(1.0, double.PositiveInfinity) does give you one and I think this is what you are looking for. Check out the documentation on the language for how the NaN is used. If you want to use the postive and negative infinities then use the double.PostiveInfinitity or the double.NegativeInfinity as NaN does not represent these values.

like image 55
Daniel Loudon Avatar answered Oct 13 '22 03:10

Daniel Loudon


There are specific representations for Negative and Positive infinities, so whatever NaN is, it doesn't represent those.

The example given in the documentation for an expression that can produce a NaN is 0.0/0.0. Whatever the result of that is, it's not some "indefinite real number" as you asserted.


Rather than assuming that Math.Pow necessarily promises to follow the conventions of another language or standard (as you've linked to in your question), you should check its own documentation that specifically states its behaviour with respect to NaNs:

Parameters        Return value
x or y = NaN.     NaN

The above is the first line from a table in the remarks section. The below appears further down in the table:

Parameters                        Return value
x = 1; y is any value except NaN. 1
like image 20
Damien_The_Unbeliever Avatar answered Oct 13 '22 03:10

Damien_The_Unbeliever