gpt4 book ai didi

javascript - 获取 JavaScript 数字的精确十进制表示

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:40:13 25 4
gpt4 key购买 nike

JavaScript 中的每个有限数都有一个精确的实数值。例如:

const x = Number.MAX_VALUE

这里,x 的精确值为 21024 - 2971 =

179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368

我们可以通过在算术中使用 x 来证明这一点:

console.log(x % 10000) // 8368

但是我怎样才能得到所有这些十进制数字呢?

我希望解决方案也适用于非整数,例如 const y = Number.EPSILON 正好是 2-52 =

0.0000000000000002220446049250313080847263336181640625

最佳答案

我发现最有效的方法是

  • 将 float 写入ArrayBuffer,然后将其作为 64 位无符号 BigInt 读回
  • 使用位运算提取符号、指数和尾数
  • 计算所需的结果乘以 10 的大幂
  • 对字符串化的 BigInt 使用字符串操作,在正确的位置插入小数点。

例如:

const SIGN_BITS = 1n
const EXPONENT_BITS = 11n
const MANTISSA_BITS = 52n
const BIAS = 1023n

export const stringify = value => {
if (typeof value !== 'number') {
throw Error('Not a number')
}

if (!Number.isFinite(value)) {
return String(value)
}

const dataView = new DataView(new ArrayBuffer(8))
dataView.setFloat64(0, value)
const bigUint64 = dataView.getBigUint64(0)

const mantissaBits = (bigUint64 >> 0n) & ((1n << MANTISSA_BITS) - 1n)
const exponentBits = (bigUint64 >> MANTISSA_BITS) & ((1n << EXPONENT_BITS) - 1n)
const signBits = (bigUint64 >> (MANTISSA_BITS + EXPONENT_BITS)) & ((1n << SIGN_BITS) - 1n)

const sign = signBits === 0b0n ? '' : '-'

const isSubnormal = exponentBits === 0b0n

// So as to keep this in integers, multiply the fraction by 2 ** 52 while subtracting
// that same power from the exponent
const m = ((isSubnormal ? 0n : 1n) << MANTISSA_BITS) + mantissaBits
const e = (isSubnormal ? 1n : exponentBits) - BIAS - MANTISSA_BITS

if (e >= 0n) {
// Pure integers, no problem
return sign + String(m << e)
}

// Multiply by a large enough power of 10 that all possible decimal digits are preserved
// when we then divide by the power of 2
const power10 = 10n ** -e
const f = (m * power10) >> -e
const pre = f / power10
const post = f % power10

if (post === 0n) {
return sign + String(pre)
}

return sign + String(pre) + '.' + String(post).padStart(Number(-e), '0').replace(/0+$/, '')
}

console.log(stringify(Number.MAX_VALUE))

这个输出:

179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368

类似地:

console.log(stringify(Number.EPSILON))

输出:

0.0000000000000002220446049250313080847263336181640625

关于javascript - 获取 JavaScript 数字的精确十进制表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44998601/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com