0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

bigintを用いてgoogolを表現しよう!!→BigInt(1e100)じゃないの?

Last updated at Posted at 2025-02-28

はじめに

今回はbigintについて学んでいた時に自分が間違った解釈をしていたことを共有したいと思います

実践

まず簡単に表記できる1e100から使ってみましょう

const googol: bigint = BigInt(1e100);
console.log(googol);

出力

10000000000000000159028911097599180468360808563945281389781327557747838772170381060813469985856815104n

となります。
BigIntって誤差ないはずじゃないの??
なぜ??

実は1e100自体はIEEE 754なのです。
したがって、次のような挙動で1e100をBigInt型にしているのです。

BigInt(1e100)
↓
BigInt(10000000000000000159028911097599180468360808563945281389781327557747838772170381060813469985856815104)
↓
10000000000000000159028911097599180468360808563945281389781327557747838772170381060813469985856815104n

丸め誤差が生じているものをBigInt型にしていることになるんですね〜

それではどうやって表現するのか?

正確な10^100を得る方法

  1. 文字列を使用:
BigInt('1' + '0'.repeat(100))
  1. BigIntの累乗を使用:
10n ** 100n
BigInt(10) ** BigInt(100)

BigInt型どうしを計算する

教訓

大きな数値を扱う場合は

  • 文字列として入力する
  • または BigInt の演算を使用する
  • 浮動小数点数を経由しない
0
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?