如何为浮点数指定舍入模式? [英] How do I specify the rounding mode for floating point numbers?

查看:397
本文介绍了如何为浮点数指定舍入模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想把浮点数整数到最接近的整数,当有一个最接近的整数时,向正无穷大方向移动。

 使用std :: num :: Float; 

$ main(){
assert_eq!( - 0.0,(-0.5).round()); //失败!

$ / code>

但是, round 说:


远离0.0的中途情况。


我还没有看到任何让我改变舍入模式的东西,但是有一些方法,对吧?

解决方案

似乎执行 Float :: round ,至少对于 f32 f64 ,转发给 roundf32 / roundf64 instrinsics ,它们本身是使用LLVM函数 llvm.round.f32 llvm.round.f64 来实现的。 llvm.round。* 文件对于如何控制四舍五入模式,c> 并没有说什么,可悲的是。在LLVM的参考文献中似乎也没有其他的东西。其他函数,我可以找到,即使提到四舍五入模式要么指定一个特定的四舍五入模式,或者说它是未定义的。



我不能找到任何关于此的可靠信息。从2011年起, LLVM邮件列表上的一篇文章讨论特定于x86的内部函数,以及针对Native Client问题的 2013博文跟踪器,似乎在谈论一个假设的内在的,它将如何很难做到可移植。



盲目地刺它:我会尝试写一个小C库,它只是链接到它。它似乎不直接受LLVM支持。


I'd like to round floating point numbers to the nearest integer, going towards positive infinity when there is a tie for "nearest integer".

use std::num::Float;

fn main() {
    assert_eq!(-0.0, (-0.5).round()); // fails!
}

However, the docs for round say:

Round half-way cases away from 0.0.

I haven't seen anything that would allow me to change the rounding mode, but there's got to be some way, right?

解决方案

It appears that the implementation of Float::round, at least for f32 and f64, forward to the roundf32/roundf64 instrinsics, which themselves are implemented using the LLVM functions llvm.round.f32 and llvm.round.f64. The documentation for llvm.round.* doesn't say anything about how to control the rounding mode, sadly. There doesn't appear to be anything else in the LLVM reference about it, either. The other functions I could find that even mentioned rounding modes either specified one particular rounding mode, or said it was undefined.

I couldn't find any solid information about this. There was a post on the LLVM mailing list from 2011 that talks about x86-specific intrinsics, and a 2013 post to the Native Client issue tracker that appears to talk about a hypothetical intrinsic and how it would be hard to do portably.

Taking a blind stab at it: I'd try writing a little C library that does it and just link to that. It doesn't appear to be directly supported in LLVM.

这篇关于如何为浮点数指定舍入模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆