finding cube root in C++?

后端 未结 12 618
自闭症患者
自闭症患者 2020-12-03 15:18

Strange things happen when i try to find the cube root of a number.

The following code returns me undefined. In cmd : -1.#IND

cout<

        
12条回答
  •  自闭症患者
    2020-12-03 15:33

    The power 1/3 is a special case. In general, non-integral powers of negative numbers are complex. It wouldn't be practical for pow to check for special cases like integer roots, and besides, 1/3 as a double is not exactly 1/3!

    I don't know about the visual C++ pow, but my man page says under errors:

    EDOM The argument x is negative and y is not an integral value. This would result in a complex number.

    You'll have to use a more specialized cube root function if you want cube roots of negative numbers - or cut corners and take absolute value, then take cube root, then multiply the sign back on.

    Note that depending on context, a negative number x to the 1/3 power is not necessarily the negative cube root you're expecting. It could just as easily be the first complex root, x^(1/3) * e^(pi*i/3). This is the convention mathematica uses; it's also reasonable to just say it's undefined.

提交回复
热议问题