优化的算法转换成十进制为" pretty的"分数 [英] Optimized algorithm for converting a decimal to a "pretty" fraction

查看:112
本文介绍了优化的算法转换成十进制为" pretty的"分数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

而不是转换一个任意的十进制到一个确切的分数(像四百三十六万二千三百六十三分之三十二万三千五百二十七),我想转换为刚刚常见易辨别(在人类可读性方面)的数量像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".

这篇关于优化的算法转换成十进制为" pretty的"分数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆