zoukankan      html  css  js  c++  java
  • 重写javascript浮点运算

    javascript中变量存储时不区分number和float类型,同一按照float存储;

    javascript使用IEEE 754-2008标准定义的64bit浮点格式存储number,decimal64对应的整形部分长度为10,小树部分长度为16;

    javascript做小数点运算会出现不精准.

    //加法运算
            var accAdd = function(num1,num2){
                var n1,n2,m;
                try{
                    n1 = num1.toString().split(".")[1].length;
                }catch(e){
                    n1 = 0;
                }
                try{
                    n2 = num2.toString().split(".")[1].length;
                }catch(e){
                    n2 = 0;
                }
                m = Math.pow(10,Math.max(n1,n2));
                return (num1*m + num2*m)/m;
            }
    
            //减法运算
            var suntr = function(num1,num2){
                var n1,n2,m,n;
                try{
                    n1 = num1.toString().split(".")[1].length;
                }catch(e){
                    n1 = 0;
                }
                try{
                    n2 = num2.toString().split(".")[1].length;
                }catch(e){
                    n2 = 0;
                }
                m = Math.pow(10,Math.max(n1,n2));
                n = (n1 > n2) ? n1 : n2;
                return ((num1*m - num2*m)/m).toFixed(n);
            }
    
            //乘法运算
            var accMul = function(num1,num2){
                var m = 0,n1,n2,
                    s1 = num1.toString(),
                    s2 = num2.toString();
                try{
                    m += s1.split(".")[1].length;
                }catch(e){
    
                }
                try{
                    m += s2.split(".")[1].length;
                }catch(e){
    
                }
                n1 = Number(s1.replace(".",""));
                n2 = Number(s2.replace(".",""));
                return n1 * n2 / Math.pow(10,m);
            }
    
            //除法运算
            var accDivi = function(num1,num2){
                var s1 = 0,s2 = 0,n1,n2;
                try{
                    s1 = num1.toString().split(".")[1].length;
                }catch(e){
    
                }
                try{
                    s2 = num2.toString().split(".")[1].length;
                }catch(e){
    
                }
                with(Math){
                    n1 = Number(num1.toString().replace(".",""));
                    n2 = Number(num2.toString().replace(".",""));
                    return (n1/n2)*Math.pow(10,s2-s1);
                }
            }
  • 相关阅读:
    CodeForcesGym 100517B Bubble Sort
    CodeForcesGym 100517H Hentium Scheduling
    BZOJ 1208: [HNOI2004]宠物收养所
    BZOJ 1503: [NOI2004]郁闷的出纳员
    BZOJ 1588: [HNOI2002]营业额统计
    sublime 3 user Settings
    sublime 3 注册码
    Why does this json4s code work in the scala repl but fail to compile?
    cat 显示指定行
    Spark Kill Application
  • 原文地址:https://www.cnblogs.com/gzzfans/p/4410508.html
Copyright © 2011-2022 走看看