Math.pow with negative numbers and non-integer powers

早过忘川 提交于 2019-11-30 13:02:28

I assume because those circumstances lead the result into complex waters, and ECMAScript is not equipped with imaginary numbers. Specifically, your example should result in something close to 1 + 1.732i, among other results. (The fact that -2 is also a possible result is besides the point - it is an accident rather than a rule.)

You can use a helper function.

In swift I faced a similar situation. Here is a proposed solution for you

func checkSquareRoot(x: Double, y: Double) -> Double {
    let result = pow(x, y)

    if x > 0 {
        return result
    } else {
        return -1 * pow( -x, y)
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!