1

Is there a boost library that supports us in converting doubles to (US style) fractional units, i.e. that converts

  • from (double) 2.56
  • to (string) '2 5/9' ?

The use case is to display the fractional number to the user whilst keeping the double representation internally. The fractional representation might very well be an approximation of the exact internal value.

ATV
  • 4,116
  • 3
  • 23
  • 42
  • possible duplicate of [How to output fraction instead of decimal number?](http://stackoverflow.com/questions/4819075/how-to-output-fraction-instead-of-decimal-number) – Cory Kramer Oct 13 '14 at 20:10
  • @Cyber Not quite the same question - the linked question is about dealing with fractional numbers and keeping the numerator/denominator representation. This question is all about converting an existing double to a (quite possibly approximated) fractional representation for readability purposes – ATV Oct 13 '14 at 20:13
  • Seems to me that the answer http://stackoverflow.com/a/4819252/1566221 by @SLeske is pretty close to answering your question, aside from not being a function in Boost. – rici Oct 13 '14 at 20:58

1 Answers1

3

Boost appears to have considered the problem and decided not to implement it.

I quote from the documentation for boost::rational

The library does not offer a conversion function from floating point to rational. A number of requests were received for such a conversion, but extensive discussions on the boost list reached the conclusion that there was no "best solution" to the problem. As there is no reason why a user of the library cannot write their own conversion function which suits their particular requirements, the decision was taken not to pick any one algorithm as "standard"…

All of this implies that we should be looking for some form of "nearest simple fraction". Algorithms to determine this sort of value do exist. However, not all applications want to work like this…

With these conflicting requirements, there is clearly no single solution which will satisfy all users. Furthermore, the algorithms involved are relatively complex and specialised, and are best implemented with a good understanding of the application requirements. All of these factors make such a function unsuitable for a general-purpose library such as this.

GP/Pari does implement a bestappr(X, B) function, which (in one of its incarnations) returns the best rational approximation of X whose denominator is less than B. (Thanks to @SLeske's answer to a similar question for the pointer.)

A Google search for "rational approximation of real numbers" yielded a number of other links, including this non-paywalled paper by Emilie Charriera and Lilian Buzera (and three cheers to Discrete Applied Mathematics for allowing open access.)

Community
  • 1
  • 1
rici
  • 234,347
  • 28
  • 237
  • 341