rat.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. // Copyright 2010 The Go 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. // This file implements multi-precision rational numbers.
  5. package big
  6. import (
  7. "fmt"
  8. "math"
  9. )
  10. // A Rat represents a quotient a/b of arbitrary precision.
  11. // The zero value for a Rat represents the value 0.
  12. //
  13. // Operations always take pointer arguments (*Rat) rather
  14. // than Rat values, and each unique Rat value requires
  15. // its own unique *Rat pointer. To "copy" a Rat value,
  16. // an existing (or newly allocated) Rat must be set to
  17. // a new value using the Rat.Set method; shallow copies
  18. // of Rats are not supported and may lead to errors.
  19. type Rat struct {
  20. // To make zero values for Rat work w/o initialization,
  21. // a zero value of b (len(b) == 0) acts like b == 1. At
  22. // the earliest opportunity (when an assignment to the Rat
  23. // is made), such uninitialized denominators are set to 1.
  24. // a.neg determines the sign of the Rat, b.neg is ignored.
  25. a, b Int
  26. }
  27. // NewRat creates a new Rat with numerator a and denominator b.
  28. func NewRat(a, b int64) *Rat {
  29. return new(Rat).SetFrac64(a, b)
  30. }
  31. // SetFloat64 sets z to exactly f and returns z.
  32. // If f is not finite, SetFloat returns nil.
  33. func (z *Rat) SetFloat64(f float64) *Rat {
  34. const expMask = 1<<11 - 1
  35. bits := math.Float64bits(f)
  36. mantissa := bits & (1<<52 - 1)
  37. exp := int((bits >> 52) & expMask)
  38. switch exp {
  39. case expMask: // non-finite
  40. return nil
  41. case 0: // denormal
  42. exp -= 1022
  43. default: // normal
  44. mantissa |= 1 << 52
  45. exp -= 1023
  46. }
  47. shift := 52 - exp
  48. // Optimization (?): partially pre-normalise.
  49. for mantissa&1 == 0 && shift > 0 {
  50. mantissa >>= 1
  51. shift--
  52. }
  53. z.a.SetUint64(mantissa)
  54. z.a.neg = f < 0
  55. z.b.Set(intOne)
  56. if shift > 0 {
  57. z.b.Lsh(&z.b, uint(shift))
  58. } else {
  59. z.a.Lsh(&z.a, uint(-shift))
  60. }
  61. return z.norm()
  62. }
  63. // quotToFloat32 returns the non-negative float32 value
  64. // nearest to the quotient a/b, using round-to-even in
  65. // halfway cases. It does not mutate its arguments.
  66. // Preconditions: b is non-zero; a and b have no common factors.
  67. func quotToFloat32(a, b nat) (f float32, exact bool) {
  68. const (
  69. // float size in bits
  70. Fsize = 32
  71. // mantissa
  72. Msize = 23
  73. Msize1 = Msize + 1 // incl. implicit 1
  74. Msize2 = Msize1 + 1
  75. // exponent
  76. Esize = Fsize - Msize1
  77. Ebias = 1<<(Esize-1) - 1
  78. Emin = 1 - Ebias
  79. Emax = Ebias
  80. )
  81. // TODO(adonovan): specialize common degenerate cases: 1.0, integers.
  82. alen := a.bitLen()
  83. if alen == 0 {
  84. return 0, true
  85. }
  86. blen := b.bitLen()
  87. if blen == 0 {
  88. panic("division by zero")
  89. }
  90. // 1. Left-shift A or B such that quotient A/B is in [1<<Msize1, 1<<(Msize2+1)
  91. // (Msize2 bits if A < B when they are left-aligned, Msize2+1 bits if A >= B).
  92. // This is 2 or 3 more than the float32 mantissa field width of Msize:
  93. // - the optional extra bit is shifted away in step 3 below.
  94. // - the high-order 1 is omitted in "normal" representation;
  95. // - the low-order 1 will be used during rounding then discarded.
  96. exp := alen - blen
  97. var a2, b2 nat
  98. a2 = a2.set(a)
  99. b2 = b2.set(b)
  100. if shift := Msize2 - exp; shift > 0 {
  101. a2 = a2.shl(a2, uint(shift))
  102. } else if shift < 0 {
  103. b2 = b2.shl(b2, uint(-shift))
  104. }
  105. // 2. Compute quotient and remainder (q, r). NB: due to the
  106. // extra shift, the low-order bit of q is logically the
  107. // high-order bit of r.
  108. var q nat
  109. q, r := q.div(a2, a2, b2) // (recycle a2)
  110. mantissa := low32(q)
  111. haveRem := len(r) > 0 // mantissa&1 && !haveRem => remainder is exactly half
  112. // 3. If quotient didn't fit in Msize2 bits, redo division by b2<<1
  113. // (in effect---we accomplish this incrementally).
  114. if mantissa>>Msize2 == 1 {
  115. if mantissa&1 == 1 {
  116. haveRem = true
  117. }
  118. mantissa >>= 1
  119. exp++
  120. }
  121. if mantissa>>Msize1 != 1 {
  122. panic(fmt.Sprintf("expected exactly %d bits of result", Msize2))
  123. }
  124. // 4. Rounding.
  125. if Emin-Msize <= exp && exp <= Emin {
  126. // Denormal case; lose 'shift' bits of precision.
  127. shift := uint(Emin - (exp - 1)) // [1..Esize1)
  128. lostbits := mantissa & (1<<shift - 1)
  129. haveRem = haveRem || lostbits != 0
  130. mantissa >>= shift
  131. exp = 2 - Ebias // == exp + shift
  132. }
  133. // Round q using round-half-to-even.
  134. exact = !haveRem
  135. if mantissa&1 != 0 {
  136. exact = false
  137. if haveRem || mantissa&2 != 0 {
  138. if mantissa++; mantissa >= 1<<Msize2 {
  139. // Complete rollover 11...1 => 100...0, so shift is safe
  140. mantissa >>= 1
  141. exp++
  142. }
  143. }
  144. }
  145. mantissa >>= 1 // discard rounding bit. Mantissa now scaled by 1<<Msize1.
  146. f = float32(math.Ldexp(float64(mantissa), exp-Msize1))
  147. if math.IsInf(float64(f), 0) {
  148. exact = false
  149. }
  150. return
  151. }
  152. // quotToFloat64 returns the non-negative float64 value
  153. // nearest to the quotient a/b, using round-to-even in
  154. // halfway cases. It does not mutate its arguments.
  155. // Preconditions: b is non-zero; a and b have no common factors.
  156. func quotToFloat64(a, b nat) (f float64, exact bool) {
  157. const (
  158. // float size in bits
  159. Fsize = 64
  160. // mantissa
  161. Msize = 52
  162. Msize1 = Msize + 1 // incl. implicit 1
  163. Msize2 = Msize1 + 1
  164. // exponent
  165. Esize = Fsize - Msize1
  166. Ebias = 1<<(Esize-1) - 1
  167. Emin = 1 - Ebias
  168. Emax = Ebias
  169. )
  170. // TODO(adonovan): specialize common degenerate cases: 1.0, integers.
  171. alen := a.bitLen()
  172. if alen == 0 {
  173. return 0, true
  174. }
  175. blen := b.bitLen()
  176. if blen == 0 {
  177. panic("division by zero")
  178. }
  179. // 1. Left-shift A or B such that quotient A/B is in [1<<Msize1, 1<<(Msize2+1)
  180. // (Msize2 bits if A < B when they are left-aligned, Msize2+1 bits if A >= B).
  181. // This is 2 or 3 more than the float64 mantissa field width of Msize:
  182. // - the optional extra bit is shifted away in step 3 below.
  183. // - the high-order 1 is omitted in "normal" representation;
  184. // - the low-order 1 will be used during rounding then discarded.
  185. exp := alen - blen
  186. var a2, b2 nat
  187. a2 = a2.set(a)
  188. b2 = b2.set(b)
  189. if shift := Msize2 - exp; shift > 0 {
  190. a2 = a2.shl(a2, uint(shift))
  191. } else if shift < 0 {
  192. b2 = b2.shl(b2, uint(-shift))
  193. }
  194. // 2. Compute quotient and remainder (q, r). NB: due to the
  195. // extra shift, the low-order bit of q is logically the
  196. // high-order bit of r.
  197. var q nat
  198. q, r := q.div(a2, a2, b2) // (recycle a2)
  199. mantissa := low64(q)
  200. haveRem := len(r) > 0 // mantissa&1 && !haveRem => remainder is exactly half
  201. // 3. If quotient didn't fit in Msize2 bits, redo division by b2<<1
  202. // (in effect---we accomplish this incrementally).
  203. if mantissa>>Msize2 == 1 {
  204. if mantissa&1 == 1 {
  205. haveRem = true
  206. }
  207. mantissa >>= 1
  208. exp++
  209. }
  210. if mantissa>>Msize1 != 1 {
  211. panic(fmt.Sprintf("expected exactly %d bits of result", Msize2))
  212. }
  213. // 4. Rounding.
  214. if Emin-Msize <= exp && exp <= Emin {
  215. // Denormal case; lose 'shift' bits of precision.
  216. shift := uint(Emin - (exp - 1)) // [1..Esize1)
  217. lostbits := mantissa & (1<<shift - 1)
  218. haveRem = haveRem || lostbits != 0
  219. mantissa >>= shift
  220. exp = 2 - Ebias // == exp + shift
  221. }
  222. // Round q using round-half-to-even.
  223. exact = !haveRem
  224. if mantissa&1 != 0 {
  225. exact = false
  226. if haveRem || mantissa&2 != 0 {
  227. if mantissa++; mantissa >= 1<<Msize2 {
  228. // Complete rollover 11...1 => 100...0, so shift is safe
  229. mantissa >>= 1
  230. exp++
  231. }
  232. }
  233. }
  234. mantissa >>= 1 // discard rounding bit. Mantissa now scaled by 1<<Msize1.
  235. f = math.Ldexp(float64(mantissa), exp-Msize1)
  236. if math.IsInf(f, 0) {
  237. exact = false
  238. }
  239. return
  240. }
  241. // Float32 returns the nearest float32 value for x and a bool indicating
  242. // whether f represents x exactly. If the magnitude of x is too large to
  243. // be represented by a float32, f is an infinity and exact is false.
  244. // The sign of f always matches the sign of x, even if f == 0.
  245. func (x *Rat) Float32() (f float32, exact bool) {
  246. b := x.b.abs
  247. if len(b) == 0 {
  248. b = natOne
  249. }
  250. f, exact = quotToFloat32(x.a.abs, b)
  251. if x.a.neg {
  252. f = -f
  253. }
  254. return
  255. }
  256. // Float64 returns the nearest float64 value for x and a bool indicating
  257. // whether f represents x exactly. If the magnitude of x is too large to
  258. // be represented by a float64, f is an infinity and exact is false.
  259. // The sign of f always matches the sign of x, even if f == 0.
  260. func (x *Rat) Float64() (f float64, exact bool) {
  261. b := x.b.abs
  262. if len(b) == 0 {
  263. b = natOne
  264. }
  265. f, exact = quotToFloat64(x.a.abs, b)
  266. if x.a.neg {
  267. f = -f
  268. }
  269. return
  270. }
  271. // SetFrac sets z to a/b and returns z.
  272. // If b == 0, SetFrac panics.
  273. func (z *Rat) SetFrac(a, b *Int) *Rat {
  274. z.a.neg = a.neg != b.neg
  275. babs := b.abs
  276. if len(babs) == 0 {
  277. panic("division by zero")
  278. }
  279. if &z.a == b || alias(z.a.abs, babs) {
  280. babs = nat(nil).set(babs) // make a copy
  281. }
  282. z.a.abs = z.a.abs.set(a.abs)
  283. z.b.abs = z.b.abs.set(babs)
  284. return z.norm()
  285. }
  286. // SetFrac64 sets z to a/b and returns z.
  287. // If b == 0, SetFrac64 panics.
  288. func (z *Rat) SetFrac64(a, b int64) *Rat {
  289. if b == 0 {
  290. panic("division by zero")
  291. }
  292. z.a.SetInt64(a)
  293. if b < 0 {
  294. b = -b
  295. z.a.neg = !z.a.neg
  296. }
  297. z.b.abs = z.b.abs.setUint64(uint64(b))
  298. return z.norm()
  299. }
  300. // SetInt sets z to x (by making a copy of x) and returns z.
  301. func (z *Rat) SetInt(x *Int) *Rat {
  302. z.a.Set(x)
  303. z.b.abs = z.b.abs.setWord(1)
  304. return z
  305. }
  306. // SetInt64 sets z to x and returns z.
  307. func (z *Rat) SetInt64(x int64) *Rat {
  308. z.a.SetInt64(x)
  309. z.b.abs = z.b.abs.setWord(1)
  310. return z
  311. }
  312. // SetUint64 sets z to x and returns z.
  313. func (z *Rat) SetUint64(x uint64) *Rat {
  314. z.a.SetUint64(x)
  315. z.b.abs = z.b.abs.setWord(1)
  316. return z
  317. }
  318. // Set sets z to x (by making a copy of x) and returns z.
  319. func (z *Rat) Set(x *Rat) *Rat {
  320. if z != x {
  321. z.a.Set(&x.a)
  322. z.b.Set(&x.b)
  323. }
  324. if len(z.b.abs) == 0 {
  325. z.b.abs = z.b.abs.setWord(1)
  326. }
  327. return z
  328. }
  329. // Abs sets z to |x| (the absolute value of x) and returns z.
  330. func (z *Rat) Abs(x *Rat) *Rat {
  331. z.Set(x)
  332. z.a.neg = false
  333. return z
  334. }
  335. // Neg sets z to -x and returns z.
  336. func (z *Rat) Neg(x *Rat) *Rat {
  337. z.Set(x)
  338. z.a.neg = len(z.a.abs) > 0 && !z.a.neg // 0 has no sign
  339. return z
  340. }
  341. // Inv sets z to 1/x and returns z.
  342. // If x == 0, Inv panics.
  343. func (z *Rat) Inv(x *Rat) *Rat {
  344. if len(x.a.abs) == 0 {
  345. panic("division by zero")
  346. }
  347. z.Set(x)
  348. z.a.abs, z.b.abs = z.b.abs, z.a.abs
  349. return z
  350. }
  351. // Sign returns:
  352. //
  353. // -1 if x < 0
  354. // 0 if x == 0
  355. // +1 if x > 0
  356. //
  357. func (x *Rat) Sign() int {
  358. return x.a.Sign()
  359. }
  360. // IsInt reports whether the denominator of x is 1.
  361. func (x *Rat) IsInt() bool {
  362. return len(x.b.abs) == 0 || x.b.abs.cmp(natOne) == 0
  363. }
  364. // Num returns the numerator of x; it may be <= 0.
  365. // The result is a reference to x's numerator; it
  366. // may change if a new value is assigned to x, and vice versa.
  367. // The sign of the numerator corresponds to the sign of x.
  368. func (x *Rat) Num() *Int {
  369. return &x.a
  370. }
  371. // Denom returns the denominator of x; it is always > 0.
  372. // The result is a reference to x's denominator, unless
  373. // x is an uninitialized (zero value) Rat, in which case
  374. // the result is a new Int of value 1. (To initialize x,
  375. // any operation that sets x will do, including x.Set(x).)
  376. // If the result is a reference to x's denominator it
  377. // may change if a new value is assigned to x, and vice versa.
  378. func (x *Rat) Denom() *Int {
  379. // Note that x.b.neg is guaranteed false.
  380. if len(x.b.abs) == 0 {
  381. // Note: If this proves problematic, we could
  382. // panic instead and require the Rat to
  383. // be explicitly initialized.
  384. return &Int{abs: nat{1}}
  385. }
  386. return &x.b
  387. }
  388. func (z *Rat) norm() *Rat {
  389. switch {
  390. case len(z.a.abs) == 0:
  391. // z == 0; normalize sign and denominator
  392. z.a.neg = false
  393. fallthrough
  394. case len(z.b.abs) == 0:
  395. // z is integer; normalize denominator
  396. z.b.abs = z.b.abs.setWord(1)
  397. default:
  398. // z is fraction; normalize numerator and denominator
  399. neg := z.a.neg
  400. z.a.neg = false
  401. z.b.neg = false
  402. if f := NewInt(0).lehmerGCD(nil, nil, &z.a, &z.b); f.Cmp(intOne) != 0 {
  403. z.a.abs, _ = z.a.abs.div(nil, z.a.abs, f.abs)
  404. z.b.abs, _ = z.b.abs.div(nil, z.b.abs, f.abs)
  405. }
  406. z.a.neg = neg
  407. }
  408. return z
  409. }
  410. // mulDenom sets z to the denominator product x*y (by taking into
  411. // account that 0 values for x or y must be interpreted as 1) and
  412. // returns z.
  413. func mulDenom(z, x, y nat) nat {
  414. switch {
  415. case len(x) == 0 && len(y) == 0:
  416. return z.setWord(1)
  417. case len(x) == 0:
  418. return z.set(y)
  419. case len(y) == 0:
  420. return z.set(x)
  421. }
  422. return z.mul(x, y)
  423. }
  424. // scaleDenom sets z to the product x*f.
  425. // If f == 0 (zero value of denominator), z is set to (a copy of) x.
  426. func (z *Int) scaleDenom(x *Int, f nat) {
  427. if len(f) == 0 {
  428. z.Set(x)
  429. return
  430. }
  431. z.abs = z.abs.mul(x.abs, f)
  432. z.neg = x.neg
  433. }
  434. // Cmp compares x and y and returns:
  435. //
  436. // -1 if x < y
  437. // 0 if x == y
  438. // +1 if x > y
  439. //
  440. func (x *Rat) Cmp(y *Rat) int {
  441. var a, b Int
  442. a.scaleDenom(&x.a, y.b.abs)
  443. b.scaleDenom(&y.a, x.b.abs)
  444. return a.Cmp(&b)
  445. }
  446. // Add sets z to the sum x+y and returns z.
  447. func (z *Rat) Add(x, y *Rat) *Rat {
  448. var a1, a2 Int
  449. a1.scaleDenom(&x.a, y.b.abs)
  450. a2.scaleDenom(&y.a, x.b.abs)
  451. z.a.Add(&a1, &a2)
  452. z.b.abs = mulDenom(z.b.abs, x.b.abs, y.b.abs)
  453. return z.norm()
  454. }
  455. // Sub sets z to the difference x-y and returns z.
  456. func (z *Rat) Sub(x, y *Rat) *Rat {
  457. var a1, a2 Int
  458. a1.scaleDenom(&x.a, y.b.abs)
  459. a2.scaleDenom(&y.a, x.b.abs)
  460. z.a.Sub(&a1, &a2)
  461. z.b.abs = mulDenom(z.b.abs, x.b.abs, y.b.abs)
  462. return z.norm()
  463. }
  464. // Mul sets z to the product x*y and returns z.
  465. func (z *Rat) Mul(x, y *Rat) *Rat {
  466. if x == y {
  467. // a squared Rat is positive and can't be reduced (no need to call norm())
  468. z.a.neg = false
  469. z.a.abs = z.a.abs.sqr(x.a.abs)
  470. if len(x.b.abs) == 0 {
  471. z.b.abs = z.b.abs.setWord(1)
  472. } else {
  473. z.b.abs = z.b.abs.sqr(x.b.abs)
  474. }
  475. return z
  476. }
  477. z.a.Mul(&x.a, &y.a)
  478. z.b.abs = mulDenom(z.b.abs, x.b.abs, y.b.abs)
  479. return z.norm()
  480. }
  481. // Quo sets z to the quotient x/y and returns z.
  482. // If y == 0, Quo panics.
  483. func (z *Rat) Quo(x, y *Rat) *Rat {
  484. if len(y.a.abs) == 0 {
  485. panic("division by zero")
  486. }
  487. var a, b Int
  488. a.scaleDenom(&x.a, y.b.abs)
  489. b.scaleDenom(&y.a, x.b.abs)
  490. z.a.abs = a.abs
  491. z.b.abs = b.abs
  492. z.a.neg = a.neg != b.neg
  493. return z.norm()
  494. }