Perl 求幂结果为“nan”
我有以下问题: 我有许多值 x,我需要计算 x^e (e 是欧拉数)。 我这样做:
$x = $x ** exp(1);
这会导致我的所有测试用例都为“nan”。
但是,如果我在执行此操作之前打印 $x 的值,然后取一个并将上面的行更改为:
$x = -12.4061063212051 ** exp(1);
它会产生完美的数字。
谁能指出我在这里做错了什么?
谢谢
PS:也许错误隐藏在其他地方,所以这是我计算 $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"
i have the following 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"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这都是关于运算符优先级的:
实际上
就像使用
Which is Fine 所看到的那样。
如果您尝试以下操作,它也会像您的程序一样失败:
而且应该如此,没有满足此条件的实数。
It's all about operator precedence:
is really
as seen using
Which is fine.
If you try the following it will also fail just as your program:
And it should, there is no real number that meets this criteria.
让我们暂时让事情变得更容易一些,假设我们正在使用
$x**2.5
。好吧,从2.5==5.0/2.0
开始,我们有$x**2.5==$x**(5.0/2.0)==($x**0.5)**5.0
。或者,换句话说,$x**2.5
与sqrt($x)
的五次方相同。由于计算机默认情况下只处理实数,您认为如果
$x==-1
会发生什么?是的......现在,如果
$x<0$
并且我们想要采用$x**exp(1)
(Perl 使用的十进制近似值 <代码>exp(1)是2.71828182845905
)?Let's make things a bit easier for the moment, and suppose that we were taking
$x**2.5
. Well, since2.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 ofsqrt($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 forexp(1)
is2.71828182845905
)?