生命的意义在于折腾

浮点数运算

javascript

1/*
2 * Auth: WANGJIAN
3 */
4var New_Math = function (){
5
6// @Function:Determine whether it is an integer or not
7// @Return type: Boolean
8// @Dependency: Integer()
9  function isInteger(Numerical_Value){
10    return Math.floor(Numerical_Value) === Numerical_Value;
11  }
12
13// @Function: Converting Floating Point to Integer
14// @Return type: number
15// @Dependency: isInteger()
16  function toInteger(floatNum){
17
18// Create objects to store integers and multiples
19    var Deposit_m_i = {
20      multiple:1,
21      integer:0,
22    }
23
24// Integer Processing Method
25    if(isInteger(floatNum)){
26      retDeposit_m_i.integer = floatNum;
27      return Deposit_m_i
28    }
29
30// Decimal processing method
31    var strfi = floatNum + '';
32    var dotPos = strfi.indexOf('.');
33    var len = strfi.substr(dotPos + 1).length;
34    var times = Math.pow(10, len);
35    var intNum = parseInt(floatNum * times + 0.5, 10);
36    Deposit_m_i.multiple = times;
37    Deposit_m_i.integer = intNum;
38    return Deposit_m_i
39  }
40
41// @Function: Enlarge decimal to integer (multiply), then reduce to decimal (divide)
42// @Return value: number
43// @Dependency: Integer()
44  function operation(a, b, op){
45
46// Processing numerical values
47    var o1 = toInteger(a);
48    var o2 = toInteger(b);
49    var n1 = o1.integer;
50    var n2 = o2.integer;
51    var t1 = o1.multiple;
52    var t2 = o2.multiple;
53    var max = t1 > t2 ? t1 : t2;
54    var result = null;
55
56// Core computing (result reception)
57// Case Judgement Four Operators
58    switch (op){
59
60// Additive operation
61      case 'add':
62        if(t1 === t2){
63          result = n1 + n2;
64        }else if(t1 > t2){
65          result = n1 + n2 * (t1 / t2);
66        }else{
67          result = n1 * (t2 / t1) + n2
68        }
69        return result / max;
70
71// Subtraction operation
72      case 'subtract':
73        if(t1 === t2){
74          result = n1 - n2
75        }else if(t1 > t2){
76          result = n1 - n2 * (t1 / t2)
77        } else {
78          result = n1 * (t2 / t1) - n2
79        }
80        return result / max;
81
82// Multiplication
83      case 'multiply':
84        result = (n1 * n2) / (t1 * t2);
85        return result;
86
87// Division
88      case 'divide':
89        result = (n1 / n2) * (t2 / t1);
90        return result
91
92    }
93  }
94
95// plus, reduce, ride and except interface
96  function add(a, b) {return operation(a, b, 'add')}
97  function subtract(a, b) {return operation(a, b,'subtract')}
98  function multiply(a, b) {return operation(a, b, 'multiply')}
99  function divide(a, b) {return operation(a, b, 'divide')}
100
101// plus, reduce, ride and except exports
102  return {
103    add: add,
104    subtract:subtract,
105    multiply:multiply,
106    divide:divide,
107  }
108}
109module.exports = New_Math
阅读量:3644发布日期:2021-06-11 16:51:39

博客描述

用于解决计算机浮点数计算的精度缺失

留言板