rat.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  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. "encoding/binary"
  8. "errors"
  9. "fmt"
  10. "math"
  11. "strings"
  12. )
  13. // A Rat represents a quotient a/b of arbitrary precision.
  14. // The zero value for a Rat represents the value 0.
  15. type Rat struct {
  16. // To make zero values for Rat work w/o initialization,
  17. // a zero value of b (len(b) == 0) acts like b == 1.
  18. // a.neg determines the sign of the Rat, b.neg is ignored.
  19. a, b Int
  20. }
  21. // NewRat creates a new Rat with numerator a and denominator b.
  22. func NewRat(a, b int64) *Rat {
  23. return new(Rat).SetFrac64(a, b)
  24. }
  25. // SetFloat64 sets z to exactly f and returns z.
  26. // If f is not finite, SetFloat returns nil.
  27. func (z *Rat) SetFloat64(f float64) *Rat {
  28. const expMask = 1<<11 - 1
  29. bits := math.Float64bits(f)
  30. mantissa := bits & (1<<52 - 1)
  31. exp := int((bits >> 52) & expMask)
  32. switch exp {
  33. case expMask: // non-finite
  34. return nil
  35. case 0: // denormal
  36. exp -= 1022
  37. default: // normal
  38. mantissa |= 1 << 52
  39. exp -= 1023
  40. }
  41. shift := 52 - exp
  42. // Optimization (?): partially pre-normalise.
  43. for mantissa&1 == 0 && shift > 0 {
  44. mantissa >>= 1
  45. shift--
  46. }
  47. z.a.SetUint64(mantissa)
  48. z.a.neg = f < 0
  49. z.b.Set(intOne)
  50. if shift > 0 {
  51. z.b.Lsh(&z.b, uint(shift))
  52. } else {
  53. z.a.Lsh(&z.a, uint(-shift))
  54. }
  55. return z.norm()
  56. }
  57. // quotToFloat32 returns the non-negative float32 value
  58. // nearest to the quotient a/b, using round-to-even in
  59. // halfway cases. It does not mutate its arguments.
  60. // Preconditions: b is non-zero; a and b have no common factors.
  61. func quotToFloat32(a, b nat) (f float32, exact bool) {
  62. const (
  63. // float size in bits
  64. Fsize = 32
  65. // mantissa
  66. Msize = 23
  67. Msize1 = Msize + 1 // incl. implicit 1
  68. Msize2 = Msize1 + 1
  69. // exponent
  70. Esize = Fsize - Msize1
  71. Ebias = 1<<(Esize-1) - 1
  72. Emin = 1 - Ebias
  73. Emax = Ebias
  74. )
  75. // TODO(adonovan): specialize common degenerate cases: 1.0, integers.
  76. alen := a.bitLen()
  77. if alen == 0 {
  78. return 0, true
  79. }
  80. blen := b.bitLen()
  81. if blen == 0 {
  82. panic("division by zero")
  83. }
  84. // 1. Left-shift A or B such that quotient A/B is in [1<<Msize1, 1<<(Msize2+1)
  85. // (Msize2 bits if A < B when they are left-aligned, Msize2+1 bits if A >= B).
  86. // This is 2 or 3 more than the float32 mantissa field width of Msize:
  87. // - the optional extra bit is shifted away in step 3 below.
  88. // - the high-order 1 is omitted in "normal" representation;
  89. // - the low-order 1 will be used during rounding then discarded.
  90. exp := alen - blen
  91. var a2, b2 nat
  92. a2 = a2.set(a)
  93. b2 = b2.set(b)
  94. if shift := Msize2 - exp; shift > 0 {
  95. a2 = a2.shl(a2, uint(shift))
  96. } else if shift < 0 {
  97. b2 = b2.shl(b2, uint(-shift))
  98. }
  99. // 2. Compute quotient and remainder (q, r). NB: due to the
  100. // extra shift, the low-order bit of q is logically the
  101. // high-order bit of r.
  102. var q nat
  103. q, r := q.div(a2, a2, b2) // (recycle a2)
  104. mantissa := low32(q)
  105. haveRem := len(r) > 0 // mantissa&1 && !haveRem => remainder is exactly half
  106. // 3. If quotient didn't fit in Msize2 bits, redo division by b2<<1
  107. // (in effect---we accomplish this incrementally).
  108. if mantissa>>Msize2 == 1 {
  109. if mantissa&1 == 1 {
  110. haveRem = true
  111. }
  112. mantissa >>= 1
  113. exp++
  114. }
  115. if mantissa>>Msize1 != 1 {
  116. panic(fmt.Sprintf("expected exactly %d bits of result", Msize2))
  117. }
  118. // 4. Rounding.
  119. if Emin-Msize <= exp && exp <= Emin {
  120. // Denormal case; lose 'shift' bits of precision.
  121. shift := uint(Emin - (exp - 1)) // [1..Esize1)
  122. lostbits := mantissa & (1<<shift - 1)
  123. haveRem = haveRem || lostbits != 0
  124. mantissa >>= shift
  125. exp = 2 - Ebias // == exp + shift
  126. }
  127. // Round q using round-half-to-even.
  128. exact = !haveRem
  129. if mantissa&1 != 0 {
  130. exact = false
  131. if haveRem || mantissa&2 != 0 {
  132. if mantissa++; mantissa >= 1<<Msize2 {
  133. // Complete rollover 11...1 => 100...0, so shift is safe
  134. mantissa >>= 1
  135. exp++
  136. }
  137. }
  138. }
  139. mantissa >>= 1 // discard rounding bit. Mantissa now scaled by 1<<Msize1.
  140. f = float32(math.Ldexp(float64(mantissa), exp-Msize1))
  141. if math.IsInf(float64(f), 0) {
  142. exact = false
  143. }
  144. return
  145. }
  146. // quotToFloat64 returns the non-negative float64 value
  147. // nearest to the quotient a/b, using round-to-even in
  148. // halfway cases. It does not mutate its arguments.
  149. // Preconditions: b is non-zero; a and b have no common factors.
  150. func quotToFloat64(a, b nat) (f float64, exact bool) {
  151. const (
  152. // float size in bits
  153. Fsize = 64
  154. // mantissa
  155. Msize = 52
  156. Msize1 = Msize + 1 // incl. implicit 1
  157. Msize2 = Msize1 + 1
  158. // exponent
  159. Esize = Fsize - Msize1
  160. Ebias = 1<<(Esize-1) - 1
  161. Emin = 1 - Ebias
  162. Emax = Ebias
  163. )
  164. // TODO(adonovan): specialize common degenerate cases: 1.0, integers.
  165. alen := a.bitLen()
  166. if alen == 0 {
  167. return 0, true
  168. }
  169. blen := b.bitLen()
  170. if blen == 0 {
  171. panic("division by zero")
  172. }
  173. // 1. Left-shift A or B such that quotient A/B is in [1<<Msize1, 1<<(Msize2+1)
  174. // (Msize2 bits if A < B when they are left-aligned, Msize2+1 bits if A >= B).
  175. // This is 2 or 3 more than the float64 mantissa field width of Msize:
  176. // - the optional extra bit is shifted away in step 3 below.
  177. // - the high-order 1 is omitted in "normal" representation;
  178. // - the low-order 1 will be used during rounding then discarded.
  179. exp := alen - blen
  180. var a2, b2 nat
  181. a2 = a2.set(a)
  182. b2 = b2.set(b)
  183. if shift := Msize2 - exp; shift > 0 {
  184. a2 = a2.shl(a2, uint(shift))
  185. } else if shift < 0 {
  186. b2 = b2.shl(b2, uint(-shift))
  187. }
  188. // 2. Compute quotient and remainder (q, r). NB: due to the
  189. // extra shift, the low-order bit of q is logically the
  190. // high-order bit of r.
  191. var q nat
  192. q, r := q.div(a2, a2, b2) // (recycle a2)
  193. mantissa := low64(q)
  194. haveRem := len(r) > 0 // mantissa&1 && !haveRem => remainder is exactly half
  195. // 3. If quotient didn't fit in Msize2 bits, redo division by b2<<1
  196. // (in effect---we accomplish this incrementally).
  197. if mantissa>>Msize2 == 1 {
  198. if mantissa&1 == 1 {
  199. haveRem = true
  200. }
  201. mantissa >>= 1
  202. exp++
  203. }
  204. if mantissa>>Msize1 != 1 {
  205. panic(fmt.Sprintf("expected exactly %d bits of result", Msize2))
  206. }
  207. // 4. Rounding.
  208. if Emin-Msize <= exp && exp <= Emin {
  209. // Denormal case; lose 'shift' bits of precision.
  210. shift := uint(Emin - (exp - 1)) // [1..Esize1)
  211. lostbits := mantissa & (1<<shift - 1)
  212. haveRem = haveRem || lostbits != 0
  213. mantissa >>= shift
  214. exp = 2 - Ebias // == exp + shift
  215. }
  216. // Round q using round-half-to-even.
  217. exact = !haveRem
  218. if mantissa&1 != 0 {
  219. exact = false
  220. if haveRem || mantissa&2 != 0 {
  221. if mantissa++; mantissa >= 1<<Msize2 {
  222. // Complete rollover 11...1 => 100...0, so shift is safe
  223. mantissa >>= 1
  224. exp++
  225. }
  226. }
  227. }
  228. mantissa >>= 1 // discard rounding bit. Mantissa now scaled by 1<<Msize1.
  229. f = math.Ldexp(float64(mantissa), exp-Msize1)
  230. if math.IsInf(f, 0) {
  231. exact = false
  232. }
  233. return
  234. }
  235. // Float32 returns the nearest float32 value for x and a bool indicating
  236. // whether f represents x exactly. If the magnitude of x is too large to
  237. // be represented by a float32, f is an infinity and exact is false.
  238. // The sign of f always matches the sign of x, even if f == 0.
  239. func (x *Rat) Float32() (f float32, exact bool) {
  240. b := x.b.abs
  241. if len(b) == 0 {
  242. b = b.set(natOne) // materialize denominator
  243. }
  244. f, exact = quotToFloat32(x.a.abs, b)
  245. if x.a.neg {
  246. f = -f
  247. }
  248. return
  249. }
  250. // Float64 returns the nearest float64 value for x and a bool indicating
  251. // whether f represents x exactly. If the magnitude of x is too large to
  252. // be represented by a float64, f is an infinity and exact is false.
  253. // The sign of f always matches the sign of x, even if f == 0.
  254. func (x *Rat) Float64() (f float64, exact bool) {
  255. b := x.b.abs
  256. if len(b) == 0 {
  257. b = b.set(natOne) // materialize denominator
  258. }
  259. f, exact = quotToFloat64(x.a.abs, b)
  260. if x.a.neg {
  261. f = -f
  262. }
  263. return
  264. }
  265. // SetFrac sets z to a/b and returns z.
  266. func (z *Rat) SetFrac(a, b *Int) *Rat {
  267. z.a.neg = a.neg != b.neg
  268. babs := b.abs
  269. if len(babs) == 0 {
  270. panic("division by zero")
  271. }
  272. if &z.a == b || alias(z.a.abs, babs) {
  273. babs = nat(nil).set(babs) // make a copy
  274. }
  275. z.a.abs = z.a.abs.set(a.abs)
  276. z.b.abs = z.b.abs.set(babs)
  277. return z.norm()
  278. }
  279. // SetFrac64 sets z to a/b and returns z.
  280. func (z *Rat) SetFrac64(a, b int64) *Rat {
  281. z.a.SetInt64(a)
  282. if b == 0 {
  283. panic("division by zero")
  284. }
  285. if b < 0 {
  286. b = -b
  287. z.a.neg = !z.a.neg
  288. }
  289. z.b.abs = z.b.abs.setUint64(uint64(b))
  290. return z.norm()
  291. }
  292. // SetInt sets z to x (by making a copy of x) and returns z.
  293. func (z *Rat) SetInt(x *Int) *Rat {
  294. z.a.Set(x)
  295. z.b.abs = z.b.abs.make(0)
  296. return z
  297. }
  298. // SetInt64 sets z to x and returns z.
  299. func (z *Rat) SetInt64(x int64) *Rat {
  300. z.a.SetInt64(x)
  301. z.b.abs = z.b.abs.make(0)
  302. return z
  303. }
  304. // Set sets z to x (by making a copy of x) and returns z.
  305. func (z *Rat) Set(x *Rat) *Rat {
  306. if z != x {
  307. z.a.Set(&x.a)
  308. z.b.Set(&x.b)
  309. }
  310. return z
  311. }
  312. // Abs sets z to |x| (the absolute value of x) and returns z.
  313. func (z *Rat) Abs(x *Rat) *Rat {
  314. z.Set(x)
  315. z.a.neg = false
  316. return z
  317. }
  318. // Neg sets z to -x and returns z.
  319. func (z *Rat) Neg(x *Rat) *Rat {
  320. z.Set(x)
  321. z.a.neg = len(z.a.abs) > 0 && !z.a.neg // 0 has no sign
  322. return z
  323. }
  324. // Inv sets z to 1/x and returns z.
  325. func (z *Rat) Inv(x *Rat) *Rat {
  326. if len(x.a.abs) == 0 {
  327. panic("division by zero")
  328. }
  329. z.Set(x)
  330. a := z.b.abs
  331. if len(a) == 0 {
  332. a = a.set(natOne) // materialize numerator
  333. }
  334. b := z.a.abs
  335. if b.cmp(natOne) == 0 {
  336. b = b.make(0) // normalize denominator
  337. }
  338. z.a.abs, z.b.abs = a, b // sign doesn't change
  339. return z
  340. }
  341. // Sign returns:
  342. //
  343. // -1 if x < 0
  344. // 0 if x == 0
  345. // +1 if x > 0
  346. //
  347. func (x *Rat) Sign() int {
  348. return x.a.Sign()
  349. }
  350. // IsInt returns true if the denominator of x is 1.
  351. func (x *Rat) IsInt() bool {
  352. return len(x.b.abs) == 0 || x.b.abs.cmp(natOne) == 0
  353. }
  354. // Num returns the numerator of x; it may be <= 0.
  355. // The result is a reference to x's numerator; it
  356. // may change if a new value is assigned to x, and vice versa.
  357. // The sign of the numerator corresponds to the sign of x.
  358. func (x *Rat) Num() *Int {
  359. return &x.a
  360. }
  361. // Denom returns the denominator of x; it is always > 0.
  362. // The result is a reference to x's denominator; it
  363. // may change if a new value is assigned to x, and vice versa.
  364. func (x *Rat) Denom() *Int {
  365. x.b.neg = false // the result is always >= 0
  366. if len(x.b.abs) == 0 {
  367. x.b.abs = x.b.abs.set(natOne) // materialize denominator
  368. }
  369. return &x.b
  370. }
  371. func (z *Rat) norm() *Rat {
  372. switch {
  373. case len(z.a.abs) == 0:
  374. // z == 0 - normalize sign and denominator
  375. z.a.neg = false
  376. z.b.abs = z.b.abs.make(0)
  377. case len(z.b.abs) == 0:
  378. // z is normalized int - nothing to do
  379. case z.b.abs.cmp(natOne) == 0:
  380. // z is int - normalize denominator
  381. z.b.abs = z.b.abs.make(0)
  382. default:
  383. neg := z.a.neg
  384. z.a.neg = false
  385. z.b.neg = false
  386. if f := NewInt(0).binaryGCD(&z.a, &z.b); f.Cmp(intOne) != 0 {
  387. z.a.abs, _ = z.a.abs.div(nil, z.a.abs, f.abs)
  388. z.b.abs, _ = z.b.abs.div(nil, z.b.abs, f.abs)
  389. if z.b.abs.cmp(natOne) == 0 {
  390. // z is int - normalize denominator
  391. z.b.abs = z.b.abs.make(0)
  392. }
  393. }
  394. z.a.neg = neg
  395. }
  396. return z
  397. }
  398. // mulDenom sets z to the denominator product x*y (by taking into
  399. // account that 0 values for x or y must be interpreted as 1) and
  400. // returns z.
  401. func mulDenom(z, x, y nat) nat {
  402. switch {
  403. case len(x) == 0:
  404. return z.set(y)
  405. case len(y) == 0:
  406. return z.set(x)
  407. }
  408. return z.mul(x, y)
  409. }
  410. // scaleDenom computes x*f.
  411. // If f == 0 (zero value of denominator), the result is (a copy of) x.
  412. func scaleDenom(x *Int, f nat) *Int {
  413. var z Int
  414. if len(f) == 0 {
  415. return z.Set(x)
  416. }
  417. z.abs = z.abs.mul(x.abs, f)
  418. z.neg = x.neg
  419. return &z
  420. }
  421. // Cmp compares x and y and returns:
  422. //
  423. // -1 if x < y
  424. // 0 if x == y
  425. // +1 if x > y
  426. //
  427. func (x *Rat) Cmp(y *Rat) int {
  428. return scaleDenom(&x.a, y.b.abs).Cmp(scaleDenom(&y.a, x.b.abs))
  429. }
  430. // Add sets z to the sum x+y and returns z.
  431. func (z *Rat) Add(x, y *Rat) *Rat {
  432. a1 := scaleDenom(&x.a, y.b.abs)
  433. a2 := scaleDenom(&y.a, x.b.abs)
  434. z.a.Add(a1, a2)
  435. z.b.abs = mulDenom(z.b.abs, x.b.abs, y.b.abs)
  436. return z.norm()
  437. }
  438. // Sub sets z to the difference x-y and returns z.
  439. func (z *Rat) Sub(x, y *Rat) *Rat {
  440. a1 := scaleDenom(&x.a, y.b.abs)
  441. a2 := scaleDenom(&y.a, x.b.abs)
  442. z.a.Sub(a1, a2)
  443. z.b.abs = mulDenom(z.b.abs, x.b.abs, y.b.abs)
  444. return z.norm()
  445. }
  446. // Mul sets z to the product x*y and returns z.
  447. func (z *Rat) Mul(x, y *Rat) *Rat {
  448. z.a.Mul(&x.a, &y.a)
  449. z.b.abs = mulDenom(z.b.abs, x.b.abs, y.b.abs)
  450. return z.norm()
  451. }
  452. // Quo sets z to the quotient x/y and returns z.
  453. // If y == 0, a division-by-zero run-time panic occurs.
  454. func (z *Rat) Quo(x, y *Rat) *Rat {
  455. if len(y.a.abs) == 0 {
  456. panic("division by zero")
  457. }
  458. a := scaleDenom(&x.a, y.b.abs)
  459. b := scaleDenom(&y.a, x.b.abs)
  460. z.a.abs = a.abs
  461. z.b.abs = b.abs
  462. z.a.neg = a.neg != b.neg
  463. return z.norm()
  464. }
  465. func ratTok(ch rune) bool {
  466. return strings.IndexRune("+-/0123456789.eE", ch) >= 0
  467. }
  468. // Scan is a support routine for fmt.Scanner. It accepts the formats
  469. // 'e', 'E', 'f', 'F', 'g', 'G', and 'v'. All formats are equivalent.
  470. func (z *Rat) Scan(s fmt.ScanState, ch rune) error {
  471. tok, err := s.Token(true, ratTok)
  472. if err != nil {
  473. return err
  474. }
  475. if strings.IndexRune("efgEFGv", ch) < 0 {
  476. return errors.New("Rat.Scan: invalid verb")
  477. }
  478. if _, ok := z.SetString(string(tok)); !ok {
  479. return errors.New("Rat.Scan: invalid syntax")
  480. }
  481. return nil
  482. }
  483. // SetString sets z to the value of s and returns z and a boolean indicating
  484. // success. s can be given as a fraction "a/b" or as a floating-point number
  485. // optionally followed by an exponent. If the operation failed, the value of
  486. // z is undefined but the returned value is nil.
  487. func (z *Rat) SetString(s string) (*Rat, bool) {
  488. if len(s) == 0 {
  489. return nil, false
  490. }
  491. // check for a quotient
  492. sep := strings.Index(s, "/")
  493. if sep >= 0 {
  494. if _, ok := z.a.SetString(s[0:sep], 10); !ok {
  495. return nil, false
  496. }
  497. s = s[sep+1:]
  498. var err error
  499. if z.b.abs, _, err = z.b.abs.scan(strings.NewReader(s), 10); err != nil {
  500. return nil, false
  501. }
  502. if len(z.b.abs) == 0 {
  503. return nil, false
  504. }
  505. return z.norm(), true
  506. }
  507. // check for a decimal point
  508. sep = strings.Index(s, ".")
  509. // check for an exponent
  510. e := strings.IndexAny(s, "eE")
  511. var exp Int
  512. if e >= 0 {
  513. if e < sep {
  514. // The E must come after the decimal point.
  515. return nil, false
  516. }
  517. if _, ok := exp.SetString(s[e+1:], 10); !ok {
  518. return nil, false
  519. }
  520. s = s[0:e]
  521. }
  522. if sep >= 0 {
  523. s = s[0:sep] + s[sep+1:]
  524. exp.Sub(&exp, NewInt(int64(len(s)-sep)))
  525. }
  526. if _, ok := z.a.SetString(s, 10); !ok {
  527. return nil, false
  528. }
  529. powTen := nat(nil).expNN(natTen, exp.abs, nil)
  530. if exp.neg {
  531. z.b.abs = powTen
  532. z.norm()
  533. } else {
  534. z.a.abs = z.a.abs.mul(z.a.abs, powTen)
  535. z.b.abs = z.b.abs.make(0)
  536. }
  537. return z, true
  538. }
  539. // String returns a string representation of x in the form "a/b" (even if b == 1).
  540. func (x *Rat) String() string {
  541. s := "/1"
  542. if len(x.b.abs) != 0 {
  543. s = "/" + x.b.abs.decimalString()
  544. }
  545. return x.a.String() + s
  546. }
  547. // RatString returns a string representation of x in the form "a/b" if b != 1,
  548. // and in the form "a" if b == 1.
  549. func (x *Rat) RatString() string {
  550. if x.IsInt() {
  551. return x.a.String()
  552. }
  553. return x.String()
  554. }
  555. // FloatString returns a string representation of x in decimal form with prec
  556. // digits of precision after the decimal point and the last digit rounded.
  557. func (x *Rat) FloatString(prec int) string {
  558. if x.IsInt() {
  559. s := x.a.String()
  560. if prec > 0 {
  561. s += "." + strings.Repeat("0", prec)
  562. }
  563. return s
  564. }
  565. // x.b.abs != 0
  566. q, r := nat(nil).div(nat(nil), x.a.abs, x.b.abs)
  567. p := natOne
  568. if prec > 0 {
  569. p = nat(nil).expNN(natTen, nat(nil).setUint64(uint64(prec)), nil)
  570. }
  571. r = r.mul(r, p)
  572. r, r2 := r.div(nat(nil), r, x.b.abs)
  573. // see if we need to round up
  574. r2 = r2.add(r2, r2)
  575. if x.b.abs.cmp(r2) <= 0 {
  576. r = r.add(r, natOne)
  577. if r.cmp(p) >= 0 {
  578. q = nat(nil).add(q, natOne)
  579. r = nat(nil).sub(r, p)
  580. }
  581. }
  582. s := q.decimalString()
  583. if x.a.neg {
  584. s = "-" + s
  585. }
  586. if prec > 0 {
  587. rs := r.decimalString()
  588. leadingZeros := prec - len(rs)
  589. s += "." + strings.Repeat("0", leadingZeros) + rs
  590. }
  591. return s
  592. }
  593. // Gob codec version. Permits backward-compatible changes to the encoding.
  594. const ratGobVersion byte = 1
  595. // GobEncode implements the gob.GobEncoder interface.
  596. func (x *Rat) GobEncode() ([]byte, error) {
  597. if x == nil {
  598. return nil, nil
  599. }
  600. buf := make([]byte, 1+4+(len(x.a.abs)+len(x.b.abs))*_S) // extra bytes for version and sign bit (1), and numerator length (4)
  601. i := x.b.abs.bytes(buf)
  602. j := x.a.abs.bytes(buf[0:i])
  603. n := i - j
  604. if int(uint32(n)) != n {
  605. // this should never happen
  606. return nil, errors.New("Rat.GobEncode: numerator too large")
  607. }
  608. binary.BigEndian.PutUint32(buf[j-4:j], uint32(n))
  609. j -= 1 + 4
  610. b := ratGobVersion << 1 // make space for sign bit
  611. if x.a.neg {
  612. b |= 1
  613. }
  614. buf[j] = b
  615. return buf[j:], nil
  616. }
  617. // GobDecode implements the gob.GobDecoder interface.
  618. func (z *Rat) GobDecode(buf []byte) error {
  619. if len(buf) == 0 {
  620. // Other side sent a nil or default value.
  621. *z = Rat{}
  622. return nil
  623. }
  624. b := buf[0]
  625. if b>>1 != ratGobVersion {
  626. return errors.New(fmt.Sprintf("Rat.GobDecode: encoding version %d not supported", b>>1))
  627. }
  628. const j = 1 + 4
  629. i := j + binary.BigEndian.Uint32(buf[j-4:j])
  630. z.a.neg = b&1 != 0
  631. z.a.abs = z.a.abs.setBytes(buf[j:i])
  632. z.b.abs = z.b.abs.setBytes(buf[i:])
  633. return nil
  634. }
  635. // MarshalText implements the encoding.TextMarshaler interface.
  636. func (r *Rat) MarshalText() (text []byte, err error) {
  637. return []byte(r.RatString()), nil
  638. }
  639. // UnmarshalText implements the encoding.TextUnmarshaler interface.
  640. func (r *Rat) UnmarshalText(text []byte) error {
  641. if _, ok := r.SetString(string(text)); !ok {
  642. return fmt.Errorf("math/big: cannot unmarshal %q into a *big.Rat", text)
  643. }
  644. return nil
  645. }