[踩坑] std::pow 与 std::cbrt

[踩坑] std::pow 与 std::cbrt

引入

求一元三次方程的根的时候,要涉及求三次方根的问题,最开始我是这么写的:

1u = std::pow(-Q/2 + std::sqrt(delta), 1.f / 3)

结果发现出来一堆 nan。

分析

参考 cppreference 上面的介绍

std::cbrt(num) is not equivalent to std::pow(num, 1.0 / 3) because the rational number 13 is typically not equal to 1.0 / 3 and std::pow cannot raise a negative base to a fractional exponent. Moreover, std::cbrt(num) usually gives more accurate results than std::pow(num, 1.0 / 3) (see example).

(本想分析一下源代码的,后来发现 libc++ 和 libstdc++ 里面都直接 __builtin_cbrt 了,找了一圈找不到具体实现,于是作罢)

只能说还是要多看文档呀。

解决

1u = std::cbrt(-Q/2 + std::sqrt(delta))

相关推荐