xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

js 大数计算

原理

JavaScript 安全整数 是 -253-1 ~ 253-1 ,即: -9007199254740991 ~ 9007199254740991; 换句话说,整数超过这个范围就会丢失精度,那超过这个范围的基本运算也别指望有多精确了;

换一种思路,用字符串表示数字,比如 "9007199254740999",不存在四舍五入精度丢失的问题,这样不管数值多大都没影响;

用数字表示字符串之后,那么数字的运算就转换成字符串的运算;

big number add

从最后一个数字开始向前依次相加,逢10进1,下一位数字相加的时候加上次计算的进位;


const add = (num1, num2) => {
  // 获取最大长度
  const len = Math.max(num1.length, num2.length);
  // 对齐
  num1 = num1.padStart(len, 0);
  num2 = num2.padStart(len, 0);

  let flag = 0;
  let result = ``;
  let temp = 0;
  for(let i=len-1; i>=0;  i--){
    temp = flag + parseInt(num1[i]) + parseInt(num2[i])
    result = (temp%10) + result 
    flag = parseInt(temp/10)
  }
  // 判断是否进位
  return result = (flag === 1 ? '1' : '') + result;
}


const n1 = "9007199254740990"
const n2 = "1229007199254740993443"

add(n1, n2);
 // "1229016206453995734433"


MathML

Mathematical Markup Language (MathML) Version 3.0 2nd Edition

W3C Recommendation 10 April 2014

https://www.w3.org/TR/MathML/

HTML var tag

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/var

<table width="100%">
  <tbody>
      <tr>
        <td id="eqnoc2"><var>E</var> = <var>m</var><var>c</var><sup>2</sup></td>
      </tr>
  </tbody>
</table>

E = mc2

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/kbd

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/code

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/samp

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/sup

<p><var>a<sup>2</sup></var> + <var>b<sup>2</sup></var> = <var>c<sup>2</sup></var></p>

a2 + b2 = c2

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/sub

H<sub>2</sub>O

H2O

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/wbr

MathJax

xml for math

https://mathjax.github.io/MathJax-demos-web/tex-chtml.html


©xgqfrms 2012-2020

www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!


原文地址:https://www.cnblogs.com/xgqfrms/p/12995736.html