四舍五入提高了Rational_cast? [英] boost rational_cast with rounding?

查看:117
本文介绍了四舍五入提高了Rational_cast?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何对rational_cast<int64_t>进行四舍五入?

当前,我正在像这样进行黑客入侵:

Currently I'm doing a hack like this:

boost::rational<int64_t> pts = ..., time_base = ...;
int64_t rounded = std::llround(boost::rational_cast<long double>(pts / time_base)); 

但是我希望能够正确"地做到这一点而不会涉及浮点数.

But I'd like to be able to do it "properly" without involving floating point.

推荐答案

舍入本身就是有损的.

想到的最快的黑客只是使用内置行为(将结果floortrunc进行)并偏移一半:

The quickest hack that comes to mind is simply using the built-in behaviour (which is floor-ing or trunc-ing the result) and offset by a half:

在Coliru上直播

#include <iostream>
#include <fstream>
#include <boost/rational.hpp>

int main() {
    using R = boost::rational<int64_t>;
    for (auto den : {5,6}) {
        std::cout << "---------\n";
        for (auto num : {1,2,3,4,5,6}) {
            R pq(num, den);
            std::cout << num << "/" << den << " = " << pq << ": " 
                      << boost::rational_cast<int64_t>(pq + R(1,2)) << "\n";
        }
    }
}

打印

---------
1/5 = 1/5: 0
2/5 = 2/5: 0
3/5 = 3/5: 1
4/5 = 4/5: 1
5/5 = 1/1: 1
6/5 = 6/5: 1
---------
1/6 = 1/6: 0
2/6 = 1/3: 0
3/6 = 1/2: 1
4/6 = 2/3: 1
5/6 = 5/6: 1
6/6 = 1/1: 1

这篇关于四舍五入提高了Rational_cast?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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