将小数转换为小数表达式的算法

时间:2013-04-06 06:12:49

标签: c haskell

假设我有一个小数点

0.30000000000000027

知道表示为分数的相同数字的最佳算法是什么 因此,某些x找到y满足c或haskell中的x=1/y

我在想

 1/3> 0.30 >1/4

迭代左右两侧,直到其中一个收敛,>变为= 所以第一次迭代看起来像

1/1  >  0.30000000000000027  > 1/somethinghere
1/2  >  0.30000000000000027  > 1/increase or decrease this 
1/3  >  0.30000000000000027 ...

我想澄清我可以轻松做到

0.30000000000000027  =  30000000000000027/  10^17

但我想做

0.30000000000000027 = 1/x

在c或haskell中

3 个答案:

答案 0 :(得分:4)

Voila(几乎正常转换为正常分数):

int gcd(int a, int b)
{
    if (a == 0) return b;
    if (b == 0) return a;

    if (a > b)
        return gcd(b, a % b);
    else
        return gcd(a, b % a);
}

struct frac {
    int num;
    int denom;
};

struct frac to_frac(double x, int precision)
{
    int denom = 1;
    for (int i = 0; i < precision; i++) {
        denom *= 10;
    }

    int num = x * denom + 0.5; // hack: round if imprecise
    int gcdiv = gcd(num, denom);

    struct frac f;
    f.num = num / gcdiv;
    f.denom = denom / gcdiv;

    return f;
}

答案 1 :(得分:3)

你有没有看过continued fractions?它们给出了非常好的数字近似值。

答案 2 :(得分:2)

不知道haskell,这里是伪代码:

raw_denom = 1/x;
print "1/" floor(raw_denom) " >= " x " >= 1/" ceil(raw_denom)
相关问题