示例工程 02-values-types-equality

另有 1 个文件未随站点发布(平台工程、二进制或超过 200KB)。

02-values-types-equality/04-number-precision-bigint/main.test.mjs

javascript · 2.1 KB

运行:02 · 浮点精度与 BigInt

点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。

import { test } from 'node:test';
import assert from 'node:assert/strict';
import { checks, run } from './main.js';
 
const byLabel = () => new Map(checks().map((r) => [r.label, r.raw]));
 
test('0.1 + 0.2 不等于 0.3,差值在 EPSILON 量级', () => {
  const m = byLabel();
  assert.equal(m.get('0.1 + 0.2 === 0.3'), false);
  assert.equal(m.get('(0.1 + 0.2).toFixed(20)'), '0.30000000000000004441');
  assert.equal(m.get('Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON'), true);
});
 
test('Number.EPSILON 是 2^-52,安全整数上限是 2^53 - 1', () => {
  const m = byLabel();
  assert.equal(m.get('Number.EPSILON === 2 ** -52'), true);
  assert.equal(m.get('Number.MAX_SAFE_INTEGER'), 9007199254740991);
  assert.equal(m.get('2 ** 53 === 2 ** 53 + 1'), true);
  assert.equal(m.get('9007199254740993 === 9007199254740992'), true, '超出安全整数后字面量被舍入');
});
 
test('BigInt 保留超出 2^53 的整数精度', () => {
  const m = byLabel();
  assert.equal(m.get("BigInt('9007199254740993')"), 9007199254740993n);
  assert.equal(m.get('typeof 1n'), 'bigint');
  assert.equal(m.get('1n === 1'), false);
  assert.equal(m.get('1n == 1'), true);
  assert.equal(m.get('1n < 2'), true);
});
 
test('BigInt 除法向零截断,与 Number 的截断方向一致', () => {
  const m = byLabel();
  assert.equal(m.get('7n / 2n(向零截断)'), 3n);
  assert.equal(m.get('-7n / 2n'), -3n);
});
 
test('BigInt 与 Number 不能混算,BigInt() 不接受非整数,JSON 不支持 BigInt', () => {
  const m = byLabel();
  assert.equal(m.get('1n + 1(不能混算)'), 'TypeError');
  assert.equal(m.get('BigInt(1.5)(不接受非整数)'), 'RangeError');
  assert.equal(m.get('JSON.stringify(1n)'), 'TypeError');
});
 
test('1e21 的默认字符串形式进入指数记法', () => {
  const m = byLabel();
  assert.equal(m.get('(1e21).toString()'), '1e+21');
});
 
test('run 返回 18 行并打印两条要点', () => {
  const out = [];
  const rows = run((s) => out.push(s));
  assert.equal(rows.length, 19);
  assert.equal(out.length, 22);
  assert.match(out.at(-1), /binary64/);
});