优化的算法转换成十进制为" pretty的"分数转换成、算法、分数、十进制

由网友(苏安)分享简介:而不是转换一个任意的十进制到一个确切的分数(像四百三十六万二千三百六十三分之三十二万三千五百二十七),我想转换为刚刚常见易辨别(在人类可读性方面)的数量像1/2,1/4, 1/8等。Rather than converting an arbitrary decimal to an exact fraction (so...

而不是转换一个任意的十进制到一个确切的分数(像四百三十六万二千三百六十三分之三十二万三千五百二十七),我想转换为刚刚常见易辨别(在人类可读性方面)的数量像1/2,1/4, 1/8等。

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.

除了使用了一系列的if-then,小于/等于等的比较,是否有更优化的技术来做到这一点?

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

编辑:在我的具体情况,近似是可以接受的。这个想法是0.251243〜0.25 = 1/4 - 在我的使用情况下,这是足够好,后者更preferable易读的快速指标(不用于计算而言,仅仅用作显示数字)。

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).

推荐答案

查找连分数逼近。维基百科有一个基本的介绍在其连分数的文章,但也有产生近似值,而产生的部分优化的算法。

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".

阅读全文

相关推荐

最新文章