JavaScript 中的负数到非整数幂
我正在编写一个脚本,该脚本必须在某一时刻执行类似的操作:Math.pow(-2,1.5)。结果应该约为 -2.82843,但 Javascript 返回 NaN
。 (我在 Google Chrome 17 和 Mozilla Firefox 11 中尝试过此操作。)如果指数是整数,例如在 Math.pow(-2,3)
中,那么 Javascript 将返回正确的答案,在本例中为 -8。正数也能正确地求非整数幂; Math.pow(2,1.5)
的计算结果约为 2.8284271247461903。有什么方法可以让Javascript计算负数的非整数幂的值吗?
I'm writing a script that has to do something like this at one point: Math.pow(-2,1.5)
. The result should be approximately -2.82843, but instead, Javascript returns NaN
. (I tried this in both Google Chrome 17 and Mozilla Firefox 11.) If the exponent is an integer, such as in Math.pow(-2,3)
, then Javascript will return the right answer, which, in this case, is -8. Positive numbers also correctly raise to non-integer powers; Math.pow(2,1.5)
evaluates to approximately 2.8284271247461903. Is there any way that I can get Javascript to calculate the value of a negative number to a non-integer power?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Math.pow(-2, 1.5)
返回 NaN,因为不存在等于 -2 的 1.5 次方的实数。有一个复数具有此属性,但Math.pow()
不使用复数进行计算。这个简单的转换证明了这种情况:
(-2)1.5 = (-2)1 * (-2)0.5 = ( -2) * sqrt(-2) = (-2) * i * sqrt(2) = -2i * sqrt(2)
Math.pow(-2, 1.5)
returns NaN because there is no real number which equals -2 taken to the power 1.5. There is a complex number with this property, butMath.pow()
doesn't do calculations using complex numbers.This simple transformation demonstrates that this is the case:
(-2)1.5 = (-2)1 * (-2)0.5 = (-2) * sqrt(-2) = (-2) * i * sqrt(2) = -2i * sqrt(2)