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

Viewed 344

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.

4 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.

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

NaN stands for "Not a Number" so a NaN return seems right to me.

This is desirable behavior. You might think Math.Pow(1, double.NaN) returning 1 as the reasonable choice, and you could make an argument in your favor when it concerns string literals, but IMHO opinion it goes down the drain when the following happens:

var i = Whatever();
var d = SomeRatherDifficultOperationYouDidntImplement();
var result = Math.Pow(i, d);

Why should this return 1? Maybe d being NaN is something that shouldn't be happening; you are swallowing a potential bug here. NaN should propagate always, chances are that some previous computation went wrong somewhere.

If you have a specific scenario where Math.Pow(1, double.NaN) needs to be 1 then use specific code for that case and comment it so its clear that its specified and required behavior.

Related