binarylog.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // Copyright (c) 2016 The mathutil Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package mathutil // import "modernc.org/mathutil"
  5. import (
  6. "math/big"
  7. )
  8. type float struct {
  9. n *big.Int
  10. fracBits int
  11. maxFracBits int
  12. }
  13. func newFloat(n *big.Int, fracBits, maxFracBits int) float {
  14. f := float{n: n, fracBits: fracBits, maxFracBits: maxFracBits}
  15. f.normalize()
  16. return f
  17. }
  18. func (f *float) normalize() {
  19. n := f.n.BitLen()
  20. if n == 0 {
  21. return
  22. }
  23. if n := f.fracBits - f.maxFracBits; n > 0 {
  24. bit := f.n.Bit(n - 1)
  25. f.n.Rsh(f.n, uint(n))
  26. if bit != 0 {
  27. f.n.Add(f.n, _1)
  28. }
  29. f.fracBits -= n
  30. }
  31. var i int
  32. for ; f.fracBits > 0 && i <= f.fracBits && f.n.Bit(i) == 0; i++ {
  33. f.fracBits--
  34. }
  35. if i != 0 {
  36. f.n.Rsh(f.n, uint(i))
  37. }
  38. }
  39. func (f *float) eq1() bool { return f.fracBits == 0 && f.n.BitLen() == 1 }
  40. func (f *float) ge2() bool { return f.n.BitLen() > f.fracBits+1 }
  41. func (f *float) div2() {
  42. f.fracBits++
  43. f.normalize()
  44. }
  45. // BinaryLog computes the binary logarithm of n. The result consists of a
  46. // characteristic and a mantissa having precision mantissaBits. The value of
  47. // the binary logarithm is
  48. //
  49. // characteristic + mantissa*(2^-mantissaBits)
  50. //
  51. // BinaryLog panics for n <= 0 or mantissaBits < 0.
  52. func BinaryLog(n *big.Int, mantissaBits int) (characteristic int, mantissa *big.Int) {
  53. if n.Sign() <= 0 || mantissaBits < 0 {
  54. panic("invalid argument of BinaryLog")
  55. }
  56. characteristic = n.BitLen() - 1
  57. mantissa = big.NewInt(0)
  58. x := newFloat(n, characteristic, mantissaBits)
  59. for ; mantissaBits != 0 && !x.eq1(); mantissaBits-- {
  60. x.sqr()
  61. mantissa.Lsh(mantissa, 1)
  62. if x.ge2() {
  63. mantissa.SetBit(mantissa, 0, 1)
  64. x.div2()
  65. }
  66. }
  67. return characteristic, mantissa
  68. }