floating point -> rational number



  • Hallo Leute, wie könnte man das lösen?

            ggT(a, b) {
                if (b == 0) {
                    return a;
                }
                return this.ggT(b, a % b);
            }
    
            print(fractional = false) {
                for (let i = 0; i < this.rows; i++) {
                    let s = "";
                    for (let j = 0; j < this.cols; j++) {
                        let v = this.matrix[i][j];
                        if (fractional && v != 0 && v != 1) {
                            let a = parseInt(v * 100.0);
                            let b = 100;
                            let ggt = this.ggT(a, b);
                            s += (a / ggt) + "/" + (b / ggt) + "  ";
                        } else {
                            s += Number(v).toFixed(2) + "  ";
                        }
                    }
                    this.appendMessage(s);
                }
                this.appendMessage("");
            }
    

    Die Ausgabe soll einmal eine Dezimalzahl (x.yy) und einmal eine Bruchzahl (xx/yy) sein.

    Zurzeit berechne ich alles mit floating points... die Ausgabe wird dann gekürzt auf zwei Nachkommastellen.

    Bei 2/3 tritt allerdings ein Problem auf:

    3.00  2.00  
    
    1.00  0.67  
    
    1.00  33/50  
    

    Hättet ihr einen Lösungsvorschlag? ... Ich weiß, dass in Computersystemen... floating points nur mit endlicher Genauigkeit dargestellt werden können, aber 33/50 sind eben nicht 2/3 (Fehler: 1 %).


Anmelden zum Antworten