Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimized algorithm for converting a decimal to a "pretty" fraction

Rather than converting an arbitrary decimal to an exact fraction (something like 323527/4362363), I am trying to convert to just common easily-discernible (in terms of human-readability) quantities like 1/2, 1/4, 1/8 etc.

Other than using a series of if-then, less than/equal to etc comparisons, are there more optimized techniques to do this?

Edit: In my particular case, approximations are acceptable. The idea is that 0.251243 ~ 0.25 = 1/4 - in my usage case, that's "good enough", with the latter more preferable for human readability in terms of a quick indicator (not used for calculation, just used as display numerics).

like image 285
ina Avatar asked Jan 13 '11 03:01

ina


2 Answers

Look up "continued fraction approximation". Wikipedia has a basic introduction in its "continued fraction" article, but there are optimized algorithms that generate the approximated value while generating the fraction.

Then pick some stopping heuristic, a combination of size of denominator and closeness of approximation, for when you're "close enough".

like image 104
Anonymous Avatar answered Nov 15 '22 06:11

Anonymous


You can use Euclidean algorithm to get Greatest Common Divisor between enumerator and denominator and divide them by it.

like image 3
Nylon Smile Avatar answered Nov 15 '22 06:11

Nylon Smile