Skip to content

Commit

Permalink
Implement toBiggestFloat
Browse files Browse the repository at this point in the history
Fixes Feature request: toBiggestInt nim-lang#34
  • Loading branch information
rotu committed Jul 26, 2022
1 parent d843ecf commit b38ff2b
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/bigints.nim
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
## Arbitrary precision integers.

import std/[algorithm, bitops, math, options]
import std/[algorithm, bitops, fenv, math, options]

type
BigInt* = object
Expand Down Expand Up @@ -1140,6 +1140,11 @@ func fastLog2*(a: BigInt): int =
return -1
bitops.fastLog2(a.limbs[^1]) + 32*(a.limbs.high)

func toBiggestFloat*(x: BigInt): BiggestFloat =
let l = mantissaDigits(BiggestFloat)+1
let shift = max(fastLog2(x) - l, 0)
let mantissa = BiggestFloat(toInt[BiggestInt](x shr shift).get())
result = mantissa * pow(2.0, BiggestFloat(shift))

func invmod*(a, modulus: BigInt): BigInt =
## Compute the modular inverse of `a` modulo `modulus`.
Expand Down
10 changes: 10 additions & 0 deletions tests/tbigints.nim
Original file line number Diff line number Diff line change
Expand Up @@ -786,6 +786,16 @@ proc main() =
doAssert pred(a, 3) == initBigInt(4)
doAssert succ(a, 3) == initBigInt(10)

block: # to float
doAssert toBiggestFloat(initBigInt("0")) == 0.0
doAssert toBiggestFloat(initBigInt("1")) == 1.0
doAssert toBiggestFloat(initBigInt("-1")) == -1.0
doAssert toBiggestFloat(initBigInt(BiggestInt.high)) == BiggestInt.high.toBiggestFloat
doAssert toBiggestFloat(initBigInt(BiggestInt.low)) == BiggestInt.low.toBiggestFloat
doAssert toBiggestFloat(initBigInt(BiggestInt.high) * initBigInt(4)) == BiggestInt.high.toBiggestFloat * 4.0
doAssert toBiggestFloat(initBigInt(BiggestInt.low) * initBigInt(4)) == BiggestInt.low.toBiggestFloat * 4.0
doAssert toBiggestFloat(initBigInt("17976931348623157") * initBigInt(10).pow(292)) == 17976931348623157e292


static: main()
main()

0 comments on commit b38ff2b

Please sign in to comment.