开发者

perl exponentiation results in "nan"

i have the f开发者_如何转开发ollowing problem: I have a number of values x and I need to compute x^e (e being euler's number). I do this:

$x = $x ** exp(1);

This results in "nan" for all of my test cases.

However if I print the values of $x before I do this and then take one and change above line to this:

$x = -12.4061063212051 ** exp(1);

it results in perfectly fine numbers.

Can anyone point out what I am doing wrong here?

Thanks

PS: Maybe the error hides somewhere else, so here is how i compute $x:

$y = #some float value taken from the output string of another program
$x = ($y/(303 * 0.0019872041));
print $x; #prints number
$x = $x ** exp(1);
print $x; #prints "nan"


It's all about operator precedence:

$x = -12.4061063212051 ** exp(1);

is really

$x = - (12.4061063212051 ** exp(1));

as seen using

$ perl -MO=Deparse,-p -e'$x = -12.4061063212051 ** $e'
($x = (-(12.4061063212051 ** $e)));
-e syntax OK

Which is fine.

If you try the following it will also fail just as your program:

$x = (- 12.4061063212051) ** exp(1);

And it should, there is no real number that meets this criteria.


Let's make things a bit easier for the moment, and suppose that we were taking $x**2.5. Well, since 2.5==5.0/2.0, we have $x**2.5==$x**(5.0/2.0)==($x**0.5)**5.0. Or, in other words, $x**2.5 is the same thing as the fifth power of sqrt($x).

Since computers tend to only deal with real numbers by default, what do you think would happen if, say $x==-1?

Yeah....now, what if $x<0$ and we wanted to take $x**exp(1) (the decimal approximation that Perl uses for exp(1) is 2.71828182845905)?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜