janet-lang / janet

A dynamic language and bytecode vm
https://janet-lang.org
MIT License
3.59k stars 231 forks source link

Arbitrary precision integers (bignum) #1376

Open sanjayjain159 opened 10 months ago

sanjayjain159 commented 10 months ago

Is there a convenient way to introduce arbitrary precision integers (bignum) in Janet? Perhaps through long strings?

sogaiu commented 10 months ago

For some use-cases, may be this is suitable?

An interest was expressed in a wrapper for GMP here, not sure if there was work on that.

I think at one point there was some comment about it NOT being likely for there to eventually be something built into Janet but I'm fuzzy on that (^^;

amano-kenji commented 10 months ago

Scheme has full-numeric tower which includes big integer and big rational numbers.

tttuuu888 commented 8 months ago

Related to this topic, I think one of Janet's current bignum-related problems is that it appears to support bignum but behaves strangely.

Below are some examples. (tested on Janet 1.33.0-f91e5994 linux/x64/gcc)

repl:24:> 11111111111111111
1.11111111111111e+16
repl:25:> 11111111111111110
1.11111111111111e+16
repl:27:> (- 11111111111111111 11111111111111110)
2
repl:28:> 1111111111111111111111111111111111
1.11111111111111e+33
repl:29:> 1111111111111111111111111111111110
1.11111111111111e+33
repl:31:> (= 1111111111111111111111111111111111 1111111111111111111111111111111110)
true
repl:34:> (- 1111111111111111111111111111111111 1111111111111111111111111111111110)
0

Wouldn't it be better to generate an error rather than allowing abnormal behavior like above?

In the long term, I hope that Janet will support bignum natively. Janet-big mentioned above looks great. But unfortunately I found same abnormal behavior like below.

repl:5:> (=  (big/int 11111111111111111111)  (big/int 11111111111111111112))
true
repl:6:> (=  (big/int "11111111111111111111")  (big/int "11111111111111111112"))
false
repl:7:> (-  (big/int 11111111111111111111)  (big/int 11111111111111111110))
<big/int 0>
repl:8:> (-  (big/int "11111111111111111111")  (big/int "11111111111111111110"))
<big/int 1>

As above, Janet-big works normally only when bignum is provided as a string. I'm not sure if this is due to a limitation of current Janet or Janet-big is missing something. But if bignum is added to Janet, It would be nice if bignum could be freely used as a number rather than a string.