簡體   English   中英

如何將f64轉換為f32並獲得最接近的近似值和下一個更大或更小的值?

[英]How can I convert a f64 to f32 and get the closest approximation and the next greater or smaller value?

該操作可能的偽代碼可能是:

fn f32_greater(x: f64) -> f32 {
    let mut y = x as f32; //I get closest
    while f64::from(y) < x {
        y = nextafter(y, f32::INFINITY);
    }
    y
}

fn f32_smaller(x: f64) -> f32 {
    let mut y = x as f32; //I get closest
    while f64::from(y) > x {
        y = nextafter(y, f32::NEG_INFINITY);
    }
    y
}

我在libc crate或f64上的方法中找不到C11的nextafter函數的等價物

對於上下文,我有一個使用f32的R樹索引。 我想搜索帶有作為f64提供的坐標的區域,所以我需要f32中包含f64值的最小可能區域。

此功能已從標准庫中刪除 一個解決方案可能是使用float_extras包 ,但我真的不喜歡這個包的方式所以我的解決方案:

mod float {
    use libc::{c_double, c_float};
    use std::{f32, f64};

    #[link_name = "m"]
    extern "C" {
        pub fn nextafter(x: c_double, y: c_double) -> c_double;
        pub fn nextafterf(x: c_float, y: c_float) -> c_float;
    // long double nextafterl(long double x, long double y);

    // double nexttoward(double x, long double y);
    // float nexttowardf(float x, long double y);
    // long double nexttowardl(long double x, long double y);
    }

    pub trait NextAfter {
        fn next_after(self, y: Self) -> Self;
    }

    impl NextAfter for f32 {
        fn next_after(self, y: Self) -> Self {
            unsafe { nextafterf(self, y) }
        }
    }

    impl NextAfter for f64 {
        fn next_after(self, y: Self) -> Self {
            unsafe { nextafter(self, y) }
        }
    }

    pub trait Succ {
        fn succ(self) -> Self;
    }

    impl Succ for f32 {
        fn succ(self) -> Self {
            self.next_after(f32::INFINITY)
        }
    }

    impl Succ for f64 {
        fn succ(self) -> Self {
            self.next_after(f64::INFINITY)
        }
    }

    pub trait Pred {
        fn pred(self) -> Self;
    }
    impl Pred for f32 {
        fn pred(self) -> Self {
            self.next_after(f32::NEG_INFINITY)
        }
    }

    impl Pred for f64 {
        fn pred(self) -> Self {
            self.next_after(f64::NEG_INFINITY)
        }
    }

}

use crate::float::{Pred, Succ};
use num_traits::cast::{FromPrimitive, ToPrimitive};

fn f32_greater<T>(x: T) -> Option<f32>
where
    T: ToPrimitive + FromPrimitive + std::cmp::PartialOrd,
{
    let mut y = x.to_f32()?;
    while T::from_f32(y)? < x {
        y = y.succ();
    }
    Some(y)
}

fn f32_smaller<T>(x: T) -> Option<f32>
where
    T: ToPrimitive + FromPrimitive + std::cmp::PartialOrd,
{
    let mut y = x.to_f32()?;
    while T::from_f32(y)? > x {
        y = y.pred();
    }
    Some(y)
}

fn main() {
    let a = 42.4242424242424242;
    println!(
        "{:.16?} < {:.16} < {:.16?}",
        f32_smaller(a),
        a,
        f32_greater(a)
    );
}

我不明白為什么他們不把它包含在數字板中

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM