将小数转换为分数,java 和 python 给出不同的输出

converting decimal into fractions, java and python gives different output

我正在尝试将小数转换为分数。我的程序适用于其他数字。然而,当试图找到 1.0923059908040425e-33 的分子和分母时,

java 给出 1/9 其中 python 给出 0.

这是我的 java 代码:

class Rational {
public static void main(String[] args) {
     println(getDenominator(convertDecimalToFraction(1.0923059908040425e-33)));
}

public static int getNumerator(String fraction) {
    return Integer.valueOf(fraction.substring(0, fraction.indexOf(".")));
}
public static int getDenominator(String fraction) {
    fraction = fraction.substring(fraction.indexOf("/") + 1);
    return Integer.valueOf(fraction.substring(0, fraction.indexOf(".")));
}

static private String convertDecimalToFraction(double x){
    if (x < 0){
        return "-" + convertDecimalToFraction(-x);
    }
    double tolerance = 1.0E-6;
    double h1=1; double h2=0;
    double k1=0; double k2=1;
    double b = x;
    do {
        double a = Math.floor(b);
        double aux = h1; h1 = a*h1+h2; h2 = aux;
        aux = k1; k1 = a*k1+k2; k2 = aux;
        b = 1/(b-a);
    } while (Math.abs(x-h1/k1) > x*tolerance);

    return h1+"/"+k1;
}
}

这是 python:

print(fractions.Fraction(1.0923059908040425e-33).limit_denominator())

我认为我的 java 代码有问题,因为我期望 0 作为正确的输出,但是分数有内置的库,我不想使用任何第三方图书馆。

java 代码几乎适用于所有输入。这个输入的唯一问题。如果有错误请指出我。 如果你能提供一个可以解决这个问题的方法或逻辑,我将不胜感激


print(fractions.Fraction(1.0923059908040425e-33)) 给出 6385627976105849/5846006549323611672814739330865132078623730171904

加上limit_denominator后变成0。 我不知道这里发生了什么..

好吧,稍微调试一下就会立即显示发生了什么。 convertDecimalToFraction returns "1.0/9.15494383825455E32" 这并不愚蠢,但是 getDenominator 只是忽略了 E32。您应该模仿 Python 中的 limit_denominator 并说如果 x<tolerance 则返回值应为 "0./1.":

static private String convertDecimalToFraction(double x){
    if (x < 0){
        return "-" + convertDecimalToFraction(-x);
    }
    double tolerance = 1.0E-6;
    if (x < tolerance) {
        return "0./1.";
    }
    double h1=1; double h2=0;
    double k1=0; double k2=1;
    double b = x;
    do {
        double a = Math.floor(b);
        double aux = h1; h1 = a*h1+h2; h2 = aux;
        aux = k1; k1 = a*k1+k2; k2 = aux;
        b = 1/(b-a);
    } while (Math.abs(x-h1/k1) > x*tolerance);

    return h1+"/"+k1;
}