ron*_*nag 5 c++ rational-number boost rounding
如何rational_cast<int64_t>进行舍入?
目前我正在做这样的黑客攻击:
boost::rational<int64_t> pts = ..., time_base = ...;
int64_t rounded = std::llround(boost::rational_cast<long double>(pts / time_base));
Run Code Online (Sandbox Code Playgroud)
但我希望能够"正确"地做到这一点而不涉及浮点.
舍入本质上是有损的。
我想到的最快的黑客方法就是简单地使用内置行为(即floor-ing 或trunc-ing 结果)并偏移一半:
#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";
}
}
}
Run Code Online (Sandbox Code Playgroud)
印刷
---------
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
151 次 |
| 最近记录: |