use crate::common::f_fmla;
use crate::cube_roots::cbrt::{CbrtBackend, GenericCbrtBackend};
#[inline(always)]
pub(crate) fn halley_refine_d(x: f64, a: f64) -> f64 {
let tx = x * x * x;
x * f_fmla(2., a, tx) / f_fmla(2., tx, a)
}
#[inline(always)]
#[allow(unused)]
pub(crate) fn halley_refine_d_fma(x: f64, a: f64) -> f64 {
let tx = x * x * x;
x * f64::mul_add(2., a, tx) / f64::mul_add(2., tx, a)
}
#[inline(always)]
const fn halley_refine(x: f32, a: f32) -> f32 {
let tx = x * x * x;
x * (tx + 2f32 * a) / (2f32 * tx + a)
}
#[inline]
pub const fn cbrtf(x: f32) -> f32 {
let u = x.to_bits();
let au = u.wrapping_shl(1);
if au < (1u32 << 24) || au >= (0xffu32 << 24) {
if au >= (0xffu32 << 24) {
return x + x;
}
if au == 0 {
return x;
}
}
const B1: u32 = 709958130;
let mut t: f32;
let mut ui: u32 = x.to_bits();
let mut hx: u32 = ui & 0x7fffffff;
hx = (hx / 3).wrapping_add(B1);
ui &= 0x80000000;
ui |= hx;
t = f32::from_bits(ui);
t = halley_refine(t, x);
halley_refine(t, x)
}
#[inline(always)]
fn cbrtf_gen_impl<B: CbrtBackend>(x: f32, backend: B) -> f32 {
let u = x.to_bits();
let au = u.wrapping_shl(1);
if au < (1u32 << 24) || au >= (0xffu32 << 24) {
if au >= (0xffu32 << 24) {
return x + x;
}
if au == 0 {
return x;
}
}
let mut ui: u32 = x.to_bits();
let mut hx: u32 = ui & 0x7fffffff;
if hx < 0x00800000 {
if hx == 0 {
return x;
}
const TWO_EXP_24: f32 = f32::from_bits(0x4b800000);
ui = (x * TWO_EXP_24).to_bits();
hx = ui & 0x7fffffff;
const B2: u32 = 642849266;
hx = (hx / 3).wrapping_add(B2);
} else {
const B1: u32 = 709958130;
hx = (hx / 3).wrapping_add(B1);
}
ui &= 0x80000000;
ui |= hx;
let mut t = f32::from_bits(ui) as f64;
let dx = x as f64;
t = backend.halley(t, dx);
backend.halley(t, dx) as f32
}
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
#[target_feature(enable = "avx", enable = "fma")]
unsafe fn cbrtf_fma_impl(x: f32) -> f32 {
use crate::cube_roots::cbrt::FmaCbrtBackend;
cbrtf_gen_impl(x, FmaCbrtBackend {})
}
#[inline]
pub fn f_cbrtf(x: f32) -> f32 {
#[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
{
cbrtf_gen_impl(x, GenericCbrtBackend {})
}
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
{
use std::sync::OnceLock;
static EXECUTOR: OnceLock<unsafe fn(f32) -> f32> = OnceLock::new();
let q = EXECUTOR.get_or_init(|| {
if std::arch::is_x86_feature_detected!("avx")
&& std::arch::is_x86_feature_detected!("fma")
{
cbrtf_fma_impl
} else {
fn def_cbrt(x: f32) -> f32 {
cbrtf_gen_impl(x, GenericCbrtBackend {})
}
def_cbrt
}
});
unsafe { q(x) }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_fcbrtf() {
assert_eq!(f_cbrtf(0.0), 0.0);
assert_eq!(f_cbrtf(-27.0), -3.0);
assert_eq!(f_cbrtf(27.0), 3.0);
assert_eq!(f_cbrtf(64.0), 4.0);
assert_eq!(f_cbrtf(-64.0), -4.0);
assert_eq!(f_cbrtf(f32::NEG_INFINITY), f32::NEG_INFINITY);
assert_eq!(f_cbrtf(f32::INFINITY), f32::INFINITY);
assert!(f_cbrtf(f32::NAN).is_nan());
}
}