Improve rationality with rounding?

How to make rational_cast<int64_t> with rounding?

I am currently 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 would like to do it β€œcorrectly” without using floating point.

+5
source share
1 answer

Rounding is inherently unprofitable.

The fastest hack that comes to mind is simply using the built-in behavior (which is floor -ing or trunc -from the result) and an offset of half:

Live on 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"; } } } 

Print

 --------- 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 
+1
source

Source: https://habr.com/ru/post/1272876/


All Articles