Arbitrary precision arithmetic with Ruby

前端 未结 5 927
醉话见心
醉话见心 2021-01-13 04:18

How the heck does Ruby do this? Does Jörg or anyone else know what\'s happening behind the scenes?

Unfortunately I don\'t know C very well so bignum.c is of little

5条回答
  •  清歌不尽
    2021-01-13 04:27

    I don't know of the implementation details so I'll cover how a basic Big Number implementation would work.

    Basically instead of relying on CPU "integers" it will create it's own using multiple CPU integers. To store arbritrary precision, well lets say you have 2 bits. So the current integer is 11. You want to add one. In normal CPU integers, this would roll over to 00

    But, for big number, instead of rolling over and keeping a "fixed" integer width, it would allocate another bit and simulate an addition so that the number becomes the correct 100.

    Try looking up how binary math can be done on paper. It's very simple and is trivial to convert to an algorithm.

提交回复
热议问题