Solução do problema de precisão de cálculo numérico no projeto de estratégia JavaScript

Autora:Bem-estar, Criado: 2020-07-09 11:31:01, Atualizado: 2023-10-28 15:32:47

img

Ao escrever estratégias JavaScript, devido a alguns problemas da própria linguagem de script, muitas vezes leva a problemas de precisão numérica nos cálculos.1 - 0.8ou0.33 * 1.1, os dados de erro serão calculados:

function main() {
    var a = 1 - 0.8
    Log(a)
   
    var c = 0.33 * 1.1
    Log(c) 
}

img

Então, como resolver esses problemas?

O progresso máximo de valores de ponto flutuante é de 17 casas decimais, mas a precisão é muito pior do que os inteiros ao realizar operações; os inteiros são convertidos em decimais ao realizar operações; e ao calcular operações decimais em Java e JavaScript, ambos Primeiro converter o decimal decimal para o binário correspondente, parte do decimal não pode ser completamente convertida em binário, eis o primeiro erro. Depois que os decimais são convertidos em binário, então a operação entre o binário é realizada para obter o resultado binário.

Para resolver este problema, eu procurei algumas soluções na Internet, e testei e usei as seguintes soluções para resolver este problema:

function mathService() {
    // addition
    this.add = function(a, b) {
        var c, d, e;
        try {
            c = a.toString().split(".")[1].length;   // Get the decimal length of a
        } catch (f) {
            c = 0;
        }
        try {
            d = b.toString().split(".")[1].length;   // Get the decimal length of b
        } catch (f) {
            d = 0;
        }
        //Find e first, multiply both a and b by e to convert to integer addition, then divide by e to restore
        return e = Math.pow(10, Math.max(c, d)), (this.mul(a, e) + this.mul(b, e)) / e;
    }
    
    // multiplication
    this.mul = function(a, b) {       
        var c = 0,
            d = a.toString(),         // Convert to string 
            e = b.toString();         // ...
        try {
            c += d.split(".")[1].length;      // c Accumulate the fractional digit length of a
        } catch (f) {}
        try {
            c += e.split(".")[1].length;      // c Accumulate the length of decimal places of b
        } catch (f) {}
        // Convert to integer multiplication, then divide by 10^c, move decimal point, restore, use integer multiplication without losing accuracy
        return Number(d.replace(".", "")) * Number(e.replace(".", "")) / Math.pow(10, c);
    }

    // Subtraction
    this.sub = function(a, b) {
        var c, d, e;
        try {
            c = a.toString().split(".")[1].length;  // Get the decimal length of a
        } catch (f) {
            c = 0;
        }
        try {
            d = b.toString().split(".")[1].length;  // Get the decimal length of b
        } catch (f) {
            d = 0;
        }
        // Same as addition
        return e = Math.pow(10, Math.max(c, d)), (this.mul(a, e) - this.mul(b, e)) / e;
    }

    // Division
    this.div = function(a, b) {
        var c, d, e = 0,
            f = 0;
        try {
            e = a.toString().split(".")[1].length;
        } catch (g) {}
        try {
            f = b.toString().split(".")[1].length;
        } catch (g) {}
        // Similarly, convert to integer, after operation, restore
        return c = Number(a.toString().replace(".", "")), d = Number(b.toString().replace(".", "")), this.mul(c / d, Math.pow(10, f - e));
    }
}

function main() {
    var obj = new mathService()
    
    var a = 1 - 0.8
    Log(a)
    
    var b = obj.sub(1, 0.8)
    Log(b)
    
    var c = 0.33 * 1.1
    Log(c)
    
    var d = obj.mul(0.33, 1.1)
    Log(d)
}

img

O princípio é converter os dois operandos a serem calculados em números inteiros para calcular para evitar problemas de precisão.

Desta forma, quando queremos que o programa para colocar uma ordem quando o preço de mercado mais uma precisão de preço mínimo, não temos que nos preocupar com a precisão numérica

function mathService() {
....    // Omitted
}

function main() {
    var obj = new mathService()
    var depth = exchange.GetDepth()
    exchange.Sell(obj.add(depth.Bids[0].Price, 0.0001), depth.Bids[0].Amount, "Buy 1 order:", depth.Bids[0]) 
}

Os comerciantes interessados podem ler o código, compreender o processo de cálculo, convidados a fazer perguntas, aprender juntos e progredir juntos.


Relacionados

Mais.