decimal.go 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477
  1. // Package decimal implements an arbitrary precision fixed-point decimal.
  2. //
  3. // The zero-value of a Decimal is 0, as you would expect.
  4. //
  5. // The best way to create a new Decimal is to use decimal.NewFromString, ex:
  6. //
  7. // n, err := decimal.NewFromString("-123.4567")
  8. // n.String() // output: "-123.4567"
  9. //
  10. // To use Decimal as part of a struct:
  11. //
  12. // type Struct struct {
  13. // Number Decimal
  14. // }
  15. //
  16. // Note: This can "only" represent numbers with a maximum of 2^31 digits after the decimal point.
  17. package decimal
  18. import (
  19. "database/sql/driver"
  20. "encoding/binary"
  21. "fmt"
  22. "math"
  23. "math/big"
  24. "strconv"
  25. "strings"
  26. )
  27. // DivisionPrecision is the number of decimal places in the result when it
  28. // doesn't divide exactly.
  29. //
  30. // Example:
  31. //
  32. // d1 := decimal.NewFromFloat(2).Div(decimal.NewFromFloat(3))
  33. // d1.String() // output: "0.6666666666666667"
  34. // d2 := decimal.NewFromFloat(2).Div(decimal.NewFromFloat(30000))
  35. // d2.String() // output: "0.0000666666666667"
  36. // d3 := decimal.NewFromFloat(20000).Div(decimal.NewFromFloat(3))
  37. // d3.String() // output: "6666.6666666666666667"
  38. // decimal.DivisionPrecision = 3
  39. // d4 := decimal.NewFromFloat(2).Div(decimal.NewFromFloat(3))
  40. // d4.String() // output: "0.667"
  41. //
  42. var DivisionPrecision = 16
  43. // MarshalJSONWithoutQuotes should be set to true if you want the decimal to
  44. // be JSON marshaled as a number, instead of as a string.
  45. // WARNING: this is dangerous for decimals with many digits, since many JSON
  46. // unmarshallers (ex: Javascript's) will unmarshal JSON numbers to IEEE 754
  47. // double-precision floating point numbers, which means you can potentially
  48. // silently lose precision.
  49. var MarshalJSONWithoutQuotes = false
  50. // Zero constant, to make computations faster.
  51. // Zero should never be compared with == or != directly, please use decimal.Equal or decimal.Cmp instead.
  52. var Zero = New(0, 1)
  53. var zeroInt = big.NewInt(0)
  54. var oneInt = big.NewInt(1)
  55. var twoInt = big.NewInt(2)
  56. var fourInt = big.NewInt(4)
  57. var fiveInt = big.NewInt(5)
  58. var tenInt = big.NewInt(10)
  59. var twentyInt = big.NewInt(20)
  60. // Decimal represents a fixed-point decimal. It is immutable.
  61. // number = value * 10 ^ exp
  62. type Decimal struct {
  63. value *big.Int
  64. // NOTE(vadim): this must be an int32, because we cast it to float64 during
  65. // calculations. If exp is 64 bit, we might lose precision.
  66. // If we cared about being able to represent every possible decimal, we
  67. // could make exp a *big.Int but it would hurt performance and numbers
  68. // like that are unrealistic.
  69. exp int32
  70. }
  71. // New returns a new fixed-point decimal, value * 10 ^ exp.
  72. func New(value int64, exp int32) Decimal {
  73. return Decimal{
  74. value: big.NewInt(value),
  75. exp: exp,
  76. }
  77. }
  78. // NewFromInt converts a int64 to Decimal.
  79. //
  80. // Example:
  81. //
  82. // NewFromInt(123).String() // output: "123"
  83. // NewFromInt(-10).String() // output: "-10"
  84. func NewFromInt(value int64) Decimal {
  85. return Decimal{
  86. value: big.NewInt(value),
  87. exp: 0,
  88. }
  89. }
  90. // NewFromInt32 converts a int32 to Decimal.
  91. //
  92. // Example:
  93. //
  94. // NewFromInt(123).String() // output: "123"
  95. // NewFromInt(-10).String() // output: "-10"
  96. func NewFromInt32(value int32) Decimal {
  97. return Decimal{
  98. value: big.NewInt(int64(value)),
  99. exp: 0,
  100. }
  101. }
  102. // NewFromBigInt returns a new Decimal from a big.Int, value * 10 ^ exp
  103. func NewFromBigInt(value *big.Int, exp int32) Decimal {
  104. return Decimal{
  105. value: big.NewInt(0).Set(value),
  106. exp: exp,
  107. }
  108. }
  109. // NewFromString returns a new Decimal from a string representation.
  110. // Trailing zeroes are not trimmed.
  111. //
  112. // Example:
  113. //
  114. // d, err := NewFromString("-123.45")
  115. // d2, err := NewFromString(".0001")
  116. // d3, err := NewFromString("1.47000")
  117. //
  118. func NewFromString(value string) (Decimal, error) {
  119. originalInput := value
  120. var intString string
  121. var exp int64
  122. // Check if number is using scientific notation
  123. eIndex := strings.IndexAny(value, "Ee")
  124. if eIndex != -1 {
  125. expInt, err := strconv.ParseInt(value[eIndex+1:], 10, 32)
  126. if err != nil {
  127. if e, ok := err.(*strconv.NumError); ok && e.Err == strconv.ErrRange {
  128. return Decimal{}, fmt.Errorf("can't convert %s to decimal: fractional part too long", value)
  129. }
  130. return Decimal{}, fmt.Errorf("can't convert %s to decimal: exponent is not numeric", value)
  131. }
  132. value = value[:eIndex]
  133. exp = expInt
  134. }
  135. parts := strings.Split(value, ".")
  136. if len(parts) == 1 {
  137. // There is no decimal point, we can just parse the original string as
  138. // an int
  139. intString = value
  140. } else if len(parts) == 2 {
  141. intString = parts[0] + parts[1]
  142. expInt := -len(parts[1])
  143. exp += int64(expInt)
  144. } else {
  145. return Decimal{}, fmt.Errorf("can't convert %s to decimal: too many .s", value)
  146. }
  147. dValue := new(big.Int)
  148. _, ok := dValue.SetString(intString, 10)
  149. if !ok {
  150. return Decimal{}, fmt.Errorf("can't convert %s to decimal", value)
  151. }
  152. if exp < math.MinInt32 || exp > math.MaxInt32 {
  153. // NOTE(vadim): I doubt a string could realistically be this long
  154. return Decimal{}, fmt.Errorf("can't convert %s to decimal: fractional part too long", originalInput)
  155. }
  156. return Decimal{
  157. value: dValue,
  158. exp: int32(exp),
  159. }, nil
  160. }
  161. // RequireFromString returns a new Decimal from a string representation
  162. // or panics if NewFromString would have returned an error.
  163. //
  164. // Example:
  165. //
  166. // d := RequireFromString("-123.45")
  167. // d2 := RequireFromString(".0001")
  168. //
  169. func RequireFromString(value string) Decimal {
  170. dec, err := NewFromString(value)
  171. if err != nil {
  172. panic(err)
  173. }
  174. return dec
  175. }
  176. // NewFromFloat converts a float64 to Decimal.
  177. //
  178. // The converted number will contain the number of significant digits that can be
  179. // represented in a float with reliable roundtrip.
  180. // This is typically 15 digits, but may be more in some cases.
  181. // See https://www.exploringbinary.com/decimal-precision-of-binary-floating-point-numbers/ for more information.
  182. //
  183. // For slightly faster conversion, use NewFromFloatWithExponent where you can specify the precision in absolute terms.
  184. //
  185. // NOTE: this will panic on NaN, +/-inf
  186. func NewFromFloat(value float64) Decimal {
  187. if value == 0 {
  188. return New(0, 0)
  189. }
  190. return newFromFloat(value, math.Float64bits(value), &float64info)
  191. }
  192. // NewFromFloat32 converts a float32 to Decimal.
  193. //
  194. // The converted number will contain the number of significant digits that can be
  195. // represented in a float with reliable roundtrip.
  196. // This is typically 6-8 digits depending on the input.
  197. // See https://www.exploringbinary.com/decimal-precision-of-binary-floating-point-numbers/ for more information.
  198. //
  199. // For slightly faster conversion, use NewFromFloatWithExponent where you can specify the precision in absolute terms.
  200. //
  201. // NOTE: this will panic on NaN, +/-inf
  202. func NewFromFloat32(value float32) Decimal {
  203. if value == 0 {
  204. return New(0, 0)
  205. }
  206. // XOR is workaround for https://github.com/golang/go/issues/26285
  207. a := math.Float32bits(value) ^ 0x80808080
  208. return newFromFloat(float64(value), uint64(a)^0x80808080, &float32info)
  209. }
  210. func newFromFloat(val float64, bits uint64, flt *floatInfo) Decimal {
  211. if math.IsNaN(val) || math.IsInf(val, 0) {
  212. panic(fmt.Sprintf("Cannot create a Decimal from %v", val))
  213. }
  214. exp := int(bits>>flt.mantbits) & (1<<flt.expbits - 1)
  215. mant := bits & (uint64(1)<<flt.mantbits - 1)
  216. switch exp {
  217. case 0:
  218. // denormalized
  219. exp++
  220. default:
  221. // add implicit top bit
  222. mant |= uint64(1) << flt.mantbits
  223. }
  224. exp += flt.bias
  225. var d decimal
  226. d.Assign(mant)
  227. d.Shift(exp - int(flt.mantbits))
  228. d.neg = bits>>(flt.expbits+flt.mantbits) != 0
  229. roundShortest(&d, mant, exp, flt)
  230. // If less than 19 digits, we can do calculation in an int64.
  231. if d.nd < 19 {
  232. tmp := int64(0)
  233. m := int64(1)
  234. for i := d.nd - 1; i >= 0; i-- {
  235. tmp += m * int64(d.d[i]-'0')
  236. m *= 10
  237. }
  238. if d.neg {
  239. tmp *= -1
  240. }
  241. return Decimal{value: big.NewInt(tmp), exp: int32(d.dp) - int32(d.nd)}
  242. }
  243. dValue := new(big.Int)
  244. dValue, ok := dValue.SetString(string(d.d[:d.nd]), 10)
  245. if ok {
  246. return Decimal{value: dValue, exp: int32(d.dp) - int32(d.nd)}
  247. }
  248. return NewFromFloatWithExponent(val, int32(d.dp)-int32(d.nd))
  249. }
  250. // NewFromFloatWithExponent converts a float64 to Decimal, with an arbitrary
  251. // number of fractional digits.
  252. //
  253. // Example:
  254. //
  255. // NewFromFloatWithExponent(123.456, -2).String() // output: "123.46"
  256. //
  257. func NewFromFloatWithExponent(value float64, exp int32) Decimal {
  258. if math.IsNaN(value) || math.IsInf(value, 0) {
  259. panic(fmt.Sprintf("Cannot create a Decimal from %v", value))
  260. }
  261. bits := math.Float64bits(value)
  262. mant := bits & (1<<52 - 1)
  263. exp2 := int32((bits >> 52) & (1<<11 - 1))
  264. sign := bits >> 63
  265. if exp2 == 0 {
  266. // specials
  267. if mant == 0 {
  268. return Decimal{}
  269. }
  270. // subnormal
  271. exp2++
  272. } else {
  273. // normal
  274. mant |= 1 << 52
  275. }
  276. exp2 -= 1023 + 52
  277. // normalizing base-2 values
  278. for mant&1 == 0 {
  279. mant = mant >> 1
  280. exp2++
  281. }
  282. // maximum number of fractional base-10 digits to represent 2^N exactly cannot be more than -N if N<0
  283. if exp < 0 && exp < exp2 {
  284. if exp2 < 0 {
  285. exp = exp2
  286. } else {
  287. exp = 0
  288. }
  289. }
  290. // representing 10^M * 2^N as 5^M * 2^(M+N)
  291. exp2 -= exp
  292. temp := big.NewInt(1)
  293. dMant := big.NewInt(int64(mant))
  294. // applying 5^M
  295. if exp > 0 {
  296. temp = temp.SetInt64(int64(exp))
  297. temp = temp.Exp(fiveInt, temp, nil)
  298. } else if exp < 0 {
  299. temp = temp.SetInt64(-int64(exp))
  300. temp = temp.Exp(fiveInt, temp, nil)
  301. dMant = dMant.Mul(dMant, temp)
  302. temp = temp.SetUint64(1)
  303. }
  304. // applying 2^(M+N)
  305. if exp2 > 0 {
  306. dMant = dMant.Lsh(dMant, uint(exp2))
  307. } else if exp2 < 0 {
  308. temp = temp.Lsh(temp, uint(-exp2))
  309. }
  310. // rounding and downscaling
  311. if exp > 0 || exp2 < 0 {
  312. halfDown := new(big.Int).Rsh(temp, 1)
  313. dMant = dMant.Add(dMant, halfDown)
  314. dMant = dMant.Quo(dMant, temp)
  315. }
  316. if sign == 1 {
  317. dMant = dMant.Neg(dMant)
  318. }
  319. return Decimal{
  320. value: dMant,
  321. exp: exp,
  322. }
  323. }
  324. // rescale returns a rescaled version of the decimal. Returned
  325. // decimal may be less precise if the given exponent is bigger
  326. // than the initial exponent of the Decimal.
  327. // NOTE: this will truncate, NOT round
  328. //
  329. // Example:
  330. //
  331. // d := New(12345, -4)
  332. // d2 := d.rescale(-1)
  333. // d3 := d2.rescale(-4)
  334. // println(d1)
  335. // println(d2)
  336. // println(d3)
  337. //
  338. // Output:
  339. //
  340. // 1.2345
  341. // 1.2
  342. // 1.2000
  343. //
  344. func (d Decimal) rescale(exp int32) Decimal {
  345. d.ensureInitialized()
  346. if d.exp == exp {
  347. return Decimal{
  348. new(big.Int).Set(d.value),
  349. d.exp,
  350. }
  351. }
  352. // NOTE(vadim): must convert exps to float64 before - to prevent overflow
  353. diff := math.Abs(float64(exp) - float64(d.exp))
  354. value := new(big.Int).Set(d.value)
  355. expScale := new(big.Int).Exp(tenInt, big.NewInt(int64(diff)), nil)
  356. if exp > d.exp {
  357. value = value.Quo(value, expScale)
  358. } else if exp < d.exp {
  359. value = value.Mul(value, expScale)
  360. }
  361. return Decimal{
  362. value: value,
  363. exp: exp,
  364. }
  365. }
  366. // Abs returns the absolute value of the decimal.
  367. func (d Decimal) Abs() Decimal {
  368. d.ensureInitialized()
  369. d2Value := new(big.Int).Abs(d.value)
  370. return Decimal{
  371. value: d2Value,
  372. exp: d.exp,
  373. }
  374. }
  375. // Add returns d + d2.
  376. func (d Decimal) Add(d2 Decimal) Decimal {
  377. rd, rd2 := RescalePair(d, d2)
  378. d3Value := new(big.Int).Add(rd.value, rd2.value)
  379. return Decimal{
  380. value: d3Value,
  381. exp: rd.exp,
  382. }
  383. }
  384. // Sub returns d - d2.
  385. func (d Decimal) Sub(d2 Decimal) Decimal {
  386. rd, rd2 := RescalePair(d, d2)
  387. d3Value := new(big.Int).Sub(rd.value, rd2.value)
  388. return Decimal{
  389. value: d3Value,
  390. exp: rd.exp,
  391. }
  392. }
  393. // Neg returns -d.
  394. func (d Decimal) Neg() Decimal {
  395. d.ensureInitialized()
  396. val := new(big.Int).Neg(d.value)
  397. return Decimal{
  398. value: val,
  399. exp: d.exp,
  400. }
  401. }
  402. // Mul returns d * d2.
  403. func (d Decimal) Mul(d2 Decimal) Decimal {
  404. d.ensureInitialized()
  405. d2.ensureInitialized()
  406. expInt64 := int64(d.exp) + int64(d2.exp)
  407. if expInt64 > math.MaxInt32 || expInt64 < math.MinInt32 {
  408. // NOTE(vadim): better to panic than give incorrect results, as
  409. // Decimals are usually used for money
  410. panic(fmt.Sprintf("exponent %v overflows an int32!", expInt64))
  411. }
  412. d3Value := new(big.Int).Mul(d.value, d2.value)
  413. return Decimal{
  414. value: d3Value,
  415. exp: int32(expInt64),
  416. }
  417. }
  418. // Shift shifts the decimal in base 10.
  419. // It shifts left when shift is positive and right if shift is negative.
  420. // In simpler terms, the given value for shift is added to the exponent
  421. // of the decimal.
  422. func (d Decimal) Shift(shift int32) Decimal {
  423. d.ensureInitialized()
  424. return Decimal{
  425. value: new(big.Int).Set(d.value),
  426. exp: d.exp + shift,
  427. }
  428. }
  429. // Div returns d / d2. If it doesn't divide exactly, the result will have
  430. // DivisionPrecision digits after the decimal point.
  431. func (d Decimal) Div(d2 Decimal) Decimal {
  432. return d.DivRound(d2, int32(DivisionPrecision))
  433. }
  434. // QuoRem does divsion with remainder
  435. // d.QuoRem(d2,precision) returns quotient q and remainder r such that
  436. // d = d2 * q + r, q an integer multiple of 10^(-precision)
  437. // 0 <= r < abs(d2) * 10 ^(-precision) if d>=0
  438. // 0 >= r > -abs(d2) * 10 ^(-precision) if d<0
  439. // Note that precision<0 is allowed as input.
  440. func (d Decimal) QuoRem(d2 Decimal, precision int32) (Decimal, Decimal) {
  441. d.ensureInitialized()
  442. d2.ensureInitialized()
  443. if d2.value.Sign() == 0 {
  444. panic("decimal division by 0")
  445. }
  446. scale := -precision
  447. e := int64(d.exp - d2.exp - scale)
  448. if e > math.MaxInt32 || e < math.MinInt32 {
  449. panic("overflow in decimal QuoRem")
  450. }
  451. var aa, bb, expo big.Int
  452. var scalerest int32
  453. // d = a 10^ea
  454. // d2 = b 10^eb
  455. if e < 0 {
  456. aa = *d.value
  457. expo.SetInt64(-e)
  458. bb.Exp(tenInt, &expo, nil)
  459. bb.Mul(d2.value, &bb)
  460. scalerest = d.exp
  461. // now aa = a
  462. // bb = b 10^(scale + eb - ea)
  463. } else {
  464. expo.SetInt64(e)
  465. aa.Exp(tenInt, &expo, nil)
  466. aa.Mul(d.value, &aa)
  467. bb = *d2.value
  468. scalerest = scale + d2.exp
  469. // now aa = a ^ (ea - eb - scale)
  470. // bb = b
  471. }
  472. var q, r big.Int
  473. q.QuoRem(&aa, &bb, &r)
  474. dq := Decimal{value: &q, exp: scale}
  475. dr := Decimal{value: &r, exp: scalerest}
  476. return dq, dr
  477. }
  478. // DivRound divides and rounds to a given precision
  479. // i.e. to an integer multiple of 10^(-precision)
  480. // for a positive quotient digit 5 is rounded up, away from 0
  481. // if the quotient is negative then digit 5 is rounded down, away from 0
  482. // Note that precision<0 is allowed as input.
  483. func (d Decimal) DivRound(d2 Decimal, precision int32) Decimal {
  484. // QuoRem already checks initialization
  485. q, r := d.QuoRem(d2, precision)
  486. // the actual rounding decision is based on comparing r*10^precision and d2/2
  487. // instead compare 2 r 10 ^precision and d2
  488. var rv2 big.Int
  489. rv2.Abs(r.value)
  490. rv2.Lsh(&rv2, 1)
  491. // now rv2 = abs(r.value) * 2
  492. r2 := Decimal{value: &rv2, exp: r.exp + precision}
  493. // r2 is now 2 * r * 10 ^ precision
  494. var c = r2.Cmp(d2.Abs())
  495. if c < 0 {
  496. return q
  497. }
  498. if d.value.Sign()*d2.value.Sign() < 0 {
  499. return q.Sub(New(1, -precision))
  500. }
  501. return q.Add(New(1, -precision))
  502. }
  503. // Mod returns d % d2.
  504. func (d Decimal) Mod(d2 Decimal) Decimal {
  505. quo := d.Div(d2).Truncate(0)
  506. return d.Sub(d2.Mul(quo))
  507. }
  508. // Pow returns d to the power d2
  509. func (d Decimal) Pow(d2 Decimal) Decimal {
  510. var temp Decimal
  511. if d2.IntPart() == 0 {
  512. return NewFromFloat(1)
  513. }
  514. temp = d.Pow(d2.Div(NewFromFloat(2)))
  515. if d2.IntPart()%2 == 0 {
  516. return temp.Mul(temp)
  517. }
  518. if d2.IntPart() > 0 {
  519. return temp.Mul(temp).Mul(d)
  520. }
  521. return temp.Mul(temp).Div(d)
  522. }
  523. // Cmp compares the numbers represented by d and d2 and returns:
  524. //
  525. // -1 if d < d2
  526. // 0 if d == d2
  527. // +1 if d > d2
  528. //
  529. func (d Decimal) Cmp(d2 Decimal) int {
  530. d.ensureInitialized()
  531. d2.ensureInitialized()
  532. if d.exp == d2.exp {
  533. return d.value.Cmp(d2.value)
  534. }
  535. rd, rd2 := RescalePair(d, d2)
  536. return rd.value.Cmp(rd2.value)
  537. }
  538. // Equal returns whether the numbers represented by d and d2 are equal.
  539. func (d Decimal) Equal(d2 Decimal) bool {
  540. return d.Cmp(d2) == 0
  541. }
  542. // Equals is deprecated, please use Equal method instead
  543. func (d Decimal) Equals(d2 Decimal) bool {
  544. return d.Equal(d2)
  545. }
  546. // GreaterThan (GT) returns true when d is greater than d2.
  547. func (d Decimal) GreaterThan(d2 Decimal) bool {
  548. return d.Cmp(d2) == 1
  549. }
  550. // GreaterThanOrEqual (GTE) returns true when d is greater than or equal to d2.
  551. func (d Decimal) GreaterThanOrEqual(d2 Decimal) bool {
  552. cmp := d.Cmp(d2)
  553. return cmp == 1 || cmp == 0
  554. }
  555. // LessThan (LT) returns true when d is less than d2.
  556. func (d Decimal) LessThan(d2 Decimal) bool {
  557. return d.Cmp(d2) == -1
  558. }
  559. // LessThanOrEqual (LTE) returns true when d is less than or equal to d2.
  560. func (d Decimal) LessThanOrEqual(d2 Decimal) bool {
  561. cmp := d.Cmp(d2)
  562. return cmp == -1 || cmp == 0
  563. }
  564. // Sign returns:
  565. //
  566. // -1 if d < 0
  567. // 0 if d == 0
  568. // +1 if d > 0
  569. //
  570. func (d Decimal) Sign() int {
  571. if d.value == nil {
  572. return 0
  573. }
  574. return d.value.Sign()
  575. }
  576. // IsPositive return
  577. //
  578. // true if d > 0
  579. // false if d == 0
  580. // false if d < 0
  581. func (d Decimal) IsPositive() bool {
  582. return d.Sign() == 1
  583. }
  584. // IsNegative return
  585. //
  586. // true if d < 0
  587. // false if d == 0
  588. // false if d > 0
  589. func (d Decimal) IsNegative() bool {
  590. return d.Sign() == -1
  591. }
  592. // IsZero return
  593. //
  594. // true if d == 0
  595. // false if d > 0
  596. // false if d < 0
  597. func (d Decimal) IsZero() bool {
  598. return d.Sign() == 0
  599. }
  600. // Exponent returns the exponent, or scale component of the decimal.
  601. func (d Decimal) Exponent() int32 {
  602. return d.exp
  603. }
  604. // Coefficient returns the coefficient of the decimal. It is scaled by 10^Exponent()
  605. func (d Decimal) Coefficient() *big.Int {
  606. d.ensureInitialized()
  607. // we copy the coefficient so that mutating the result does not mutate the
  608. // Decimal.
  609. return big.NewInt(0).Set(d.value)
  610. }
  611. // IntPart returns the integer component of the decimal.
  612. func (d Decimal) IntPart() int64 {
  613. scaledD := d.rescale(0)
  614. return scaledD.value.Int64()
  615. }
  616. // BigInt returns integer component of the decimal as a BigInt.
  617. func (d Decimal) BigInt() *big.Int {
  618. scaledD := d.rescale(0)
  619. i := &big.Int{}
  620. i.SetString(scaledD.String(), 10)
  621. return i
  622. }
  623. // BigFloat returns decimal as BigFloat.
  624. // Be aware that casting decimal to BigFloat might cause a loss of precision.
  625. func (d Decimal) BigFloat() *big.Float {
  626. f := &big.Float{}
  627. f.SetString(d.String())
  628. return f
  629. }
  630. // Rat returns a rational number representation of the decimal.
  631. func (d Decimal) Rat() *big.Rat {
  632. d.ensureInitialized()
  633. if d.exp <= 0 {
  634. // NOTE(vadim): must negate after casting to prevent int32 overflow
  635. denom := new(big.Int).Exp(tenInt, big.NewInt(-int64(d.exp)), nil)
  636. return new(big.Rat).SetFrac(d.value, denom)
  637. }
  638. mul := new(big.Int).Exp(tenInt, big.NewInt(int64(d.exp)), nil)
  639. num := new(big.Int).Mul(d.value, mul)
  640. return new(big.Rat).SetFrac(num, oneInt)
  641. }
  642. // Float64 returns the nearest float64 value for d and a bool indicating
  643. // whether f represents d exactly.
  644. // For more details, see the documentation for big.Rat.Float64
  645. func (d Decimal) Float64() (f float64, exact bool) {
  646. return d.Rat().Float64()
  647. }
  648. // String returns the string representation of the decimal
  649. // with the fixed point.
  650. //
  651. // Example:
  652. //
  653. // d := New(-12345, -3)
  654. // println(d.String())
  655. //
  656. // Output:
  657. //
  658. // -12.345
  659. //
  660. func (d Decimal) String() string {
  661. return d.string(true)
  662. }
  663. // StringFixed returns a rounded fixed-point string with places digits after
  664. // the decimal point.
  665. //
  666. // Example:
  667. //
  668. // NewFromFloat(0).StringFixed(2) // output: "0.00"
  669. // NewFromFloat(0).StringFixed(0) // output: "0"
  670. // NewFromFloat(5.45).StringFixed(0) // output: "5"
  671. // NewFromFloat(5.45).StringFixed(1) // output: "5.5"
  672. // NewFromFloat(5.45).StringFixed(2) // output: "5.45"
  673. // NewFromFloat(5.45).StringFixed(3) // output: "5.450"
  674. // NewFromFloat(545).StringFixed(-1) // output: "550"
  675. //
  676. func (d Decimal) StringFixed(places int32) string {
  677. rounded := d.Round(places)
  678. return rounded.string(false)
  679. }
  680. // StringFixedBank returns a banker rounded fixed-point string with places digits
  681. // after the decimal point.
  682. //
  683. // Example:
  684. //
  685. // NewFromFloat(0).StringFixedBank(2) // output: "0.00"
  686. // NewFromFloat(0).StringFixedBank(0) // output: "0"
  687. // NewFromFloat(5.45).StringFixedBank(0) // output: "5"
  688. // NewFromFloat(5.45).StringFixedBank(1) // output: "5.4"
  689. // NewFromFloat(5.45).StringFixedBank(2) // output: "5.45"
  690. // NewFromFloat(5.45).StringFixedBank(3) // output: "5.450"
  691. // NewFromFloat(545).StringFixedBank(-1) // output: "540"
  692. //
  693. func (d Decimal) StringFixedBank(places int32) string {
  694. rounded := d.RoundBank(places)
  695. return rounded.string(false)
  696. }
  697. // StringFixedCash returns a Swedish/Cash rounded fixed-point string. For
  698. // more details see the documentation at function RoundCash.
  699. func (d Decimal) StringFixedCash(interval uint8) string {
  700. rounded := d.RoundCash(interval)
  701. return rounded.string(false)
  702. }
  703. // Round rounds the decimal to places decimal places.
  704. // If places < 0, it will round the integer part to the nearest 10^(-places).
  705. //
  706. // Example:
  707. //
  708. // NewFromFloat(5.45).Round(1).String() // output: "5.5"
  709. // NewFromFloat(545).Round(-1).String() // output: "550"
  710. //
  711. func (d Decimal) Round(places int32) Decimal {
  712. // truncate to places + 1
  713. ret := d.rescale(-places - 1)
  714. // add sign(d) * 0.5
  715. if ret.value.Sign() < 0 {
  716. ret.value.Sub(ret.value, fiveInt)
  717. } else {
  718. ret.value.Add(ret.value, fiveInt)
  719. }
  720. // floor for positive numbers, ceil for negative numbers
  721. _, m := ret.value.DivMod(ret.value, tenInt, new(big.Int))
  722. ret.exp++
  723. if ret.value.Sign() < 0 && m.Cmp(zeroInt) != 0 {
  724. ret.value.Add(ret.value, oneInt)
  725. }
  726. return ret
  727. }
  728. // RoundBank rounds the decimal to places decimal places.
  729. // If the final digit to round is equidistant from the nearest two integers the
  730. // rounded value is taken as the even number
  731. //
  732. // If places < 0, it will round the integer part to the nearest 10^(-places).
  733. //
  734. // Examples:
  735. //
  736. // NewFromFloat(5.45).Round(1).String() // output: "5.4"
  737. // NewFromFloat(545).Round(-1).String() // output: "540"
  738. // NewFromFloat(5.46).Round(1).String() // output: "5.5"
  739. // NewFromFloat(546).Round(-1).String() // output: "550"
  740. // NewFromFloat(5.55).Round(1).String() // output: "5.6"
  741. // NewFromFloat(555).Round(-1).String() // output: "560"
  742. //
  743. func (d Decimal) RoundBank(places int32) Decimal {
  744. round := d.Round(places)
  745. remainder := d.Sub(round).Abs()
  746. half := New(5, -places-1)
  747. if remainder.Cmp(half) == 0 && round.value.Bit(0) != 0 {
  748. if round.value.Sign() < 0 {
  749. round.value.Add(round.value, oneInt)
  750. } else {
  751. round.value.Sub(round.value, oneInt)
  752. }
  753. }
  754. return round
  755. }
  756. // RoundCash aka Cash/Penny/öre rounding rounds decimal to a specific
  757. // interval. The amount payable for a cash transaction is rounded to the nearest
  758. // multiple of the minimum currency unit available. The following intervals are
  759. // available: 5, 10, 25, 50 and 100; any other number throws a panic.
  760. // 5: 5 cent rounding 3.43 => 3.45
  761. // 10: 10 cent rounding 3.45 => 3.50 (5 gets rounded up)
  762. // 25: 25 cent rounding 3.41 => 3.50
  763. // 50: 50 cent rounding 3.75 => 4.00
  764. // 100: 100 cent rounding 3.50 => 4.00
  765. // For more details: https://en.wikipedia.org/wiki/Cash_rounding
  766. func (d Decimal) RoundCash(interval uint8) Decimal {
  767. var iVal *big.Int
  768. switch interval {
  769. case 5:
  770. iVal = twentyInt
  771. case 10:
  772. iVal = tenInt
  773. case 25:
  774. iVal = fourInt
  775. case 50:
  776. iVal = twoInt
  777. case 100:
  778. iVal = oneInt
  779. default:
  780. panic(fmt.Sprintf("Decimal does not support this Cash rounding interval `%d`. Supported: 5, 10, 25, 50, 100", interval))
  781. }
  782. dVal := Decimal{
  783. value: iVal,
  784. }
  785. // TODO: optimize those calculations to reduce the high allocations (~29 allocs).
  786. return d.Mul(dVal).Round(0).Div(dVal).Truncate(2)
  787. }
  788. // Floor returns the nearest integer value less than or equal to d.
  789. func (d Decimal) Floor() Decimal {
  790. d.ensureInitialized()
  791. if d.exp >= 0 {
  792. return d
  793. }
  794. exp := big.NewInt(10)
  795. // NOTE(vadim): must negate after casting to prevent int32 overflow
  796. exp.Exp(exp, big.NewInt(-int64(d.exp)), nil)
  797. z := new(big.Int).Div(d.value, exp)
  798. return Decimal{value: z, exp: 0}
  799. }
  800. // Ceil returns the nearest integer value greater than or equal to d.
  801. func (d Decimal) Ceil() Decimal {
  802. d.ensureInitialized()
  803. if d.exp >= 0 {
  804. return d
  805. }
  806. exp := big.NewInt(10)
  807. // NOTE(vadim): must negate after casting to prevent int32 overflow
  808. exp.Exp(exp, big.NewInt(-int64(d.exp)), nil)
  809. z, m := new(big.Int).DivMod(d.value, exp, new(big.Int))
  810. if m.Cmp(zeroInt) != 0 {
  811. z.Add(z, oneInt)
  812. }
  813. return Decimal{value: z, exp: 0}
  814. }
  815. // Truncate truncates off digits from the number, without rounding.
  816. //
  817. // NOTE: precision is the last digit that will not be truncated (must be >= 0).
  818. //
  819. // Example:
  820. //
  821. // decimal.NewFromString("123.456").Truncate(2).String() // "123.45"
  822. //
  823. func (d Decimal) Truncate(precision int32) Decimal {
  824. d.ensureInitialized()
  825. if precision >= 0 && -precision > d.exp {
  826. return d.rescale(-precision)
  827. }
  828. return d
  829. }
  830. // UnmarshalJSON implements the json.Unmarshaler interface.
  831. func (d *Decimal) UnmarshalJSON(decimalBytes []byte) error {
  832. if string(decimalBytes) == "null" {
  833. return nil
  834. }
  835. str, err := unquoteIfQuoted(decimalBytes)
  836. if err != nil {
  837. return fmt.Errorf("error decoding string '%s': %s", decimalBytes, err)
  838. }
  839. decimal, err := NewFromString(str)
  840. *d = decimal
  841. if err != nil {
  842. return fmt.Errorf("error decoding string '%s': %s", str, err)
  843. }
  844. return nil
  845. }
  846. // MarshalJSON implements the json.Marshaler interface.
  847. func (d Decimal) MarshalJSON() ([]byte, error) {
  848. var str string
  849. if MarshalJSONWithoutQuotes {
  850. str = d.String()
  851. } else {
  852. str = "\"" + d.String() + "\""
  853. }
  854. return []byte(str), nil
  855. }
  856. // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. As a string representation
  857. // is already used when encoding to text, this method stores that string as []byte
  858. func (d *Decimal) UnmarshalBinary(data []byte) error {
  859. // Extract the exponent
  860. d.exp = int32(binary.BigEndian.Uint32(data[:4]))
  861. // Extract the value
  862. d.value = new(big.Int)
  863. return d.value.GobDecode(data[4:])
  864. }
  865. // MarshalBinary implements the encoding.BinaryMarshaler interface.
  866. func (d Decimal) MarshalBinary() (data []byte, err error) {
  867. // Write the exponent first since it's a fixed size
  868. v1 := make([]byte, 4)
  869. binary.BigEndian.PutUint32(v1, uint32(d.exp))
  870. // Add the value
  871. var v2 []byte
  872. if v2, err = d.value.GobEncode(); err != nil {
  873. return
  874. }
  875. // Return the byte array
  876. data = append(v1, v2...)
  877. return
  878. }
  879. // Scan implements the sql.Scanner interface for database deserialization.
  880. func (d *Decimal) Scan(value interface{}) error {
  881. // first try to see if the data is stored in database as a Numeric datatype
  882. switch v := value.(type) {
  883. case float32:
  884. *d = NewFromFloat(float64(v))
  885. return nil
  886. case float64:
  887. // numeric in sqlite3 sends us float64
  888. *d = NewFromFloat(v)
  889. return nil
  890. case int64:
  891. // at least in sqlite3 when the value is 0 in db, the data is sent
  892. // to us as an int64 instead of a float64 ...
  893. *d = New(v, 0)
  894. return nil
  895. default:
  896. // default is trying to interpret value stored as string
  897. str, err := unquoteIfQuoted(v)
  898. if err != nil {
  899. return err
  900. }
  901. *d, err = NewFromString(str)
  902. return err
  903. }
  904. }
  905. // Value implements the driver.Valuer interface for database serialization.
  906. func (d Decimal) Value() (driver.Value, error) {
  907. return d.String(), nil
  908. }
  909. // UnmarshalText implements the encoding.TextUnmarshaler interface for XML
  910. // deserialization.
  911. func (d *Decimal) UnmarshalText(text []byte) error {
  912. str := string(text)
  913. dec, err := NewFromString(str)
  914. *d = dec
  915. if err != nil {
  916. return fmt.Errorf("error decoding string '%s': %s", str, err)
  917. }
  918. return nil
  919. }
  920. // MarshalText implements the encoding.TextMarshaler interface for XML
  921. // serialization.
  922. func (d Decimal) MarshalText() (text []byte, err error) {
  923. return []byte(d.String()), nil
  924. }
  925. // GobEncode implements the gob.GobEncoder interface for gob serialization.
  926. func (d Decimal) GobEncode() ([]byte, error) {
  927. return d.MarshalBinary()
  928. }
  929. // GobDecode implements the gob.GobDecoder interface for gob serialization.
  930. func (d *Decimal) GobDecode(data []byte) error {
  931. return d.UnmarshalBinary(data)
  932. }
  933. // StringScaled first scales the decimal then calls .String() on it.
  934. // NOTE: buggy, unintuitive, and DEPRECATED! Use StringFixed instead.
  935. func (d Decimal) StringScaled(exp int32) string {
  936. return d.rescale(exp).String()
  937. }
  938. func (d Decimal) string(trimTrailingZeros bool) string {
  939. if d.exp >= 0 {
  940. return d.rescale(0).value.String()
  941. }
  942. abs := new(big.Int).Abs(d.value)
  943. str := abs.String()
  944. var intPart, fractionalPart string
  945. // NOTE(vadim): this cast to int will cause bugs if d.exp == INT_MIN
  946. // and you are on a 32-bit machine. Won't fix this super-edge case.
  947. dExpInt := int(d.exp)
  948. if len(str) > -dExpInt {
  949. intPart = str[:len(str)+dExpInt]
  950. fractionalPart = str[len(str)+dExpInt:]
  951. } else {
  952. intPart = "0"
  953. num0s := -dExpInt - len(str)
  954. fractionalPart = strings.Repeat("0", num0s) + str
  955. }
  956. if trimTrailingZeros {
  957. i := len(fractionalPart) - 1
  958. for ; i >= 0; i-- {
  959. if fractionalPart[i] != '0' {
  960. break
  961. }
  962. }
  963. fractionalPart = fractionalPart[:i+1]
  964. }
  965. number := intPart
  966. if len(fractionalPart) > 0 {
  967. number += "." + fractionalPart
  968. }
  969. if d.value.Sign() < 0 {
  970. return "-" + number
  971. }
  972. return number
  973. }
  974. func (d *Decimal) ensureInitialized() {
  975. if d.value == nil {
  976. d.value = new(big.Int)
  977. }
  978. }
  979. // Min returns the smallest Decimal that was passed in the arguments.
  980. //
  981. // To call this function with an array, you must do:
  982. //
  983. // Min(arr[0], arr[1:]...)
  984. //
  985. // This makes it harder to accidentally call Min with 0 arguments.
  986. func Min(first Decimal, rest ...Decimal) Decimal {
  987. ans := first
  988. for _, item := range rest {
  989. if item.Cmp(ans) < 0 {
  990. ans = item
  991. }
  992. }
  993. return ans
  994. }
  995. // Max returns the largest Decimal that was passed in the arguments.
  996. //
  997. // To call this function with an array, you must do:
  998. //
  999. // Max(arr[0], arr[1:]...)
  1000. //
  1001. // This makes it harder to accidentally call Max with 0 arguments.
  1002. func Max(first Decimal, rest ...Decimal) Decimal {
  1003. ans := first
  1004. for _, item := range rest {
  1005. if item.Cmp(ans) > 0 {
  1006. ans = item
  1007. }
  1008. }
  1009. return ans
  1010. }
  1011. // Sum returns the combined total of the provided first and rest Decimals
  1012. func Sum(first Decimal, rest ...Decimal) Decimal {
  1013. total := first
  1014. for _, item := range rest {
  1015. total = total.Add(item)
  1016. }
  1017. return total
  1018. }
  1019. // Avg returns the average value of the provided first and rest Decimals
  1020. func Avg(first Decimal, rest ...Decimal) Decimal {
  1021. count := New(int64(len(rest)+1), 0)
  1022. sum := Sum(first, rest...)
  1023. return sum.Div(count)
  1024. }
  1025. // RescalePair rescales two decimals to common exponential value (minimal exp of both decimals)
  1026. func RescalePair(d1 Decimal, d2 Decimal) (Decimal, Decimal) {
  1027. d1.ensureInitialized()
  1028. d2.ensureInitialized()
  1029. if d1.exp == d2.exp {
  1030. return d1, d2
  1031. }
  1032. baseScale := min(d1.exp, d2.exp)
  1033. if baseScale != d1.exp {
  1034. return d1.rescale(baseScale), d2
  1035. }
  1036. return d1, d2.rescale(baseScale)
  1037. }
  1038. func min(x, y int32) int32 {
  1039. if x >= y {
  1040. return y
  1041. }
  1042. return x
  1043. }
  1044. func unquoteIfQuoted(value interface{}) (string, error) {
  1045. var bytes []byte
  1046. switch v := value.(type) {
  1047. case string:
  1048. bytes = []byte(v)
  1049. case []byte:
  1050. bytes = v
  1051. default:
  1052. return "", fmt.Errorf("could not convert value '%+v' to byte array of type '%T'",
  1053. value, value)
  1054. }
  1055. // If the amount is quoted, strip the quotes
  1056. if len(bytes) > 2 && bytes[0] == '"' && bytes[len(bytes)-1] == '"' {
  1057. bytes = bytes[1 : len(bytes)-1]
  1058. }
  1059. return string(bytes), nil
  1060. }
  1061. // NullDecimal represents a nullable decimal with compatibility for
  1062. // scanning null values from the database.
  1063. type NullDecimal struct {
  1064. Decimal Decimal
  1065. Valid bool
  1066. }
  1067. // Scan implements the sql.Scanner interface for database deserialization.
  1068. func (d *NullDecimal) Scan(value interface{}) error {
  1069. if value == nil {
  1070. d.Valid = false
  1071. return nil
  1072. }
  1073. d.Valid = true
  1074. return d.Decimal.Scan(value)
  1075. }
  1076. // Value implements the driver.Valuer interface for database serialization.
  1077. func (d NullDecimal) Value() (driver.Value, error) {
  1078. if !d.Valid {
  1079. return nil, nil
  1080. }
  1081. return d.Decimal.Value()
  1082. }
  1083. // UnmarshalJSON implements the json.Unmarshaler interface.
  1084. func (d *NullDecimal) UnmarshalJSON(decimalBytes []byte) error {
  1085. if string(decimalBytes) == "null" {
  1086. d.Valid = false
  1087. return nil
  1088. }
  1089. d.Valid = true
  1090. return d.Decimal.UnmarshalJSON(decimalBytes)
  1091. }
  1092. // MarshalJSON implements the json.Marshaler interface.
  1093. func (d NullDecimal) MarshalJSON() ([]byte, error) {
  1094. if !d.Valid {
  1095. return []byte("null"), nil
  1096. }
  1097. return d.Decimal.MarshalJSON()
  1098. }
  1099. // Trig functions
  1100. // Atan returns the arctangent, in radians, of x.
  1101. func (d Decimal) Atan() Decimal {
  1102. if d.Equal(NewFromFloat(0.0)) {
  1103. return d
  1104. }
  1105. if d.GreaterThan(NewFromFloat(0.0)) {
  1106. return d.satan()
  1107. }
  1108. return d.Neg().satan().Neg()
  1109. }
  1110. func (d Decimal) xatan() Decimal {
  1111. P0 := NewFromFloat(-8.750608600031904122785e-01)
  1112. P1 := NewFromFloat(-1.615753718733365076637e+01)
  1113. P2 := NewFromFloat(-7.500855792314704667340e+01)
  1114. P3 := NewFromFloat(-1.228866684490136173410e+02)
  1115. P4 := NewFromFloat(-6.485021904942025371773e+01)
  1116. Q0 := NewFromFloat(2.485846490142306297962e+01)
  1117. Q1 := NewFromFloat(1.650270098316988542046e+02)
  1118. Q2 := NewFromFloat(4.328810604912902668951e+02)
  1119. Q3 := NewFromFloat(4.853903996359136964868e+02)
  1120. Q4 := NewFromFloat(1.945506571482613964425e+02)
  1121. z := d.Mul(d)
  1122. b1 := P0.Mul(z).Add(P1).Mul(z).Add(P2).Mul(z).Add(P3).Mul(z).Add(P4).Mul(z)
  1123. b2 := z.Add(Q0).Mul(z).Add(Q1).Mul(z).Add(Q2).Mul(z).Add(Q3).Mul(z).Add(Q4)
  1124. z = b1.Div(b2)
  1125. z = d.Mul(z).Add(d)
  1126. return z
  1127. }
  1128. // satan reduces its argument (known to be positive)
  1129. // to the range [0, 0.66] and calls xatan.
  1130. func (d Decimal) satan() Decimal {
  1131. Morebits := NewFromFloat(6.123233995736765886130e-17) // pi/2 = PIO2 + Morebits
  1132. Tan3pio8 := NewFromFloat(2.41421356237309504880) // tan(3*pi/8)
  1133. pi := NewFromFloat(3.14159265358979323846264338327950288419716939937510582097494459)
  1134. if d.LessThanOrEqual(NewFromFloat(0.66)) {
  1135. return d.xatan()
  1136. }
  1137. if d.GreaterThan(Tan3pio8) {
  1138. return pi.Div(NewFromFloat(2.0)).Sub(NewFromFloat(1.0).Div(d).xatan()).Add(Morebits)
  1139. }
  1140. return pi.Div(NewFromFloat(4.0)).Add((d.Sub(NewFromFloat(1.0)).Div(d.Add(NewFromFloat(1.0)))).xatan()).Add(NewFromFloat(0.5).Mul(Morebits))
  1141. }
  1142. // sin coefficients
  1143. var _sin = [...]Decimal{
  1144. NewFromFloat(1.58962301576546568060e-10), // 0x3de5d8fd1fd19ccd
  1145. NewFromFloat(-2.50507477628578072866e-8), // 0xbe5ae5e5a9291f5d
  1146. NewFromFloat(2.75573136213857245213e-6), // 0x3ec71de3567d48a1
  1147. NewFromFloat(-1.98412698295895385996e-4), // 0xbf2a01a019bfdf03
  1148. NewFromFloat(8.33333333332211858878e-3), // 0x3f8111111110f7d0
  1149. NewFromFloat(-1.66666666666666307295e-1), // 0xbfc5555555555548
  1150. }
  1151. // Sin returns the sine of the radian argument x.
  1152. func (d Decimal) Sin() Decimal {
  1153. PI4A := NewFromFloat(7.85398125648498535156e-1) // 0x3fe921fb40000000, Pi/4 split into three parts
  1154. PI4B := NewFromFloat(3.77489470793079817668e-8) // 0x3e64442d00000000,
  1155. PI4C := NewFromFloat(2.69515142907905952645e-15) // 0x3ce8469898cc5170,
  1156. M4PI := NewFromFloat(1.273239544735162542821171882678754627704620361328125) // 4/pi
  1157. if d.Equal(NewFromFloat(0.0)) {
  1158. return d
  1159. }
  1160. // make argument positive but save the sign
  1161. sign := false
  1162. if d.LessThan(NewFromFloat(0.0)) {
  1163. d = d.Neg()
  1164. sign = true
  1165. }
  1166. j := d.Mul(M4PI).IntPart() // integer part of x/(Pi/4), as integer for tests on the phase angle
  1167. y := NewFromFloat(float64(j)) // integer part of x/(Pi/4), as float
  1168. // map zeros to origin
  1169. if j&1 == 1 {
  1170. j++
  1171. y = y.Add(NewFromFloat(1.0))
  1172. }
  1173. j &= 7 // octant modulo 2Pi radians (360 degrees)
  1174. // reflect in x axis
  1175. if j > 3 {
  1176. sign = !sign
  1177. j -= 4
  1178. }
  1179. z := d.Sub(y.Mul(PI4A)).Sub(y.Mul(PI4B)).Sub(y.Mul(PI4C)) // Extended precision modular arithmetic
  1180. zz := z.Mul(z)
  1181. if j == 1 || j == 2 {
  1182. w := zz.Mul(zz).Mul(_cos[0].Mul(zz).Add(_cos[1]).Mul(zz).Add(_cos[2]).Mul(zz).Add(_cos[3]).Mul(zz).Add(_cos[4]).Mul(zz).Add(_cos[5]))
  1183. y = NewFromFloat(1.0).Sub(NewFromFloat(0.5).Mul(zz)).Add(w)
  1184. } else {
  1185. y = z.Add(z.Mul(zz).Mul(_sin[0].Mul(zz).Add(_sin[1]).Mul(zz).Add(_sin[2]).Mul(zz).Add(_sin[3]).Mul(zz).Add(_sin[4]).Mul(zz).Add(_sin[5])))
  1186. }
  1187. if sign {
  1188. y = y.Neg()
  1189. }
  1190. return y
  1191. }
  1192. // cos coefficients
  1193. var _cos = [...]Decimal{
  1194. NewFromFloat(-1.13585365213876817300e-11), // 0xbda8fa49a0861a9b
  1195. NewFromFloat(2.08757008419747316778e-9), // 0x3e21ee9d7b4e3f05
  1196. NewFromFloat(-2.75573141792967388112e-7), // 0xbe927e4f7eac4bc6
  1197. NewFromFloat(2.48015872888517045348e-5), // 0x3efa01a019c844f5
  1198. NewFromFloat(-1.38888888888730564116e-3), // 0xbf56c16c16c14f91
  1199. NewFromFloat(4.16666666666665929218e-2), // 0x3fa555555555554b
  1200. }
  1201. // Cos returns the cosine of the radian argument x.
  1202. func (d Decimal) Cos() Decimal {
  1203. PI4A := NewFromFloat(7.85398125648498535156e-1) // 0x3fe921fb40000000, Pi/4 split into three parts
  1204. PI4B := NewFromFloat(3.77489470793079817668e-8) // 0x3e64442d00000000,
  1205. PI4C := NewFromFloat(2.69515142907905952645e-15) // 0x3ce8469898cc5170,
  1206. M4PI := NewFromFloat(1.273239544735162542821171882678754627704620361328125) // 4/pi
  1207. // make argument positive
  1208. sign := false
  1209. if d.LessThan(NewFromFloat(0.0)) {
  1210. d = d.Neg()
  1211. }
  1212. j := d.Mul(M4PI).IntPart() // integer part of x/(Pi/4), as integer for tests on the phase angle
  1213. y := NewFromFloat(float64(j)) // integer part of x/(Pi/4), as float
  1214. // map zeros to origin
  1215. if j&1 == 1 {
  1216. j++
  1217. y = y.Add(NewFromFloat(1.0))
  1218. }
  1219. j &= 7 // octant modulo 2Pi radians (360 degrees)
  1220. // reflect in x axis
  1221. if j > 3 {
  1222. sign = !sign
  1223. j -= 4
  1224. }
  1225. if j > 1 {
  1226. sign = !sign
  1227. }
  1228. z := d.Sub(y.Mul(PI4A)).Sub(y.Mul(PI4B)).Sub(y.Mul(PI4C)) // Extended precision modular arithmetic
  1229. zz := z.Mul(z)
  1230. if j == 1 || j == 2 {
  1231. y = z.Add(z.Mul(zz).Mul(_sin[0].Mul(zz).Add(_sin[1]).Mul(zz).Add(_sin[2]).Mul(zz).Add(_sin[3]).Mul(zz).Add(_sin[4]).Mul(zz).Add(_sin[5])))
  1232. } else {
  1233. w := zz.Mul(zz).Mul(_cos[0].Mul(zz).Add(_cos[1]).Mul(zz).Add(_cos[2]).Mul(zz).Add(_cos[3]).Mul(zz).Add(_cos[4]).Mul(zz).Add(_cos[5]))
  1234. y = NewFromFloat(1.0).Sub(NewFromFloat(0.5).Mul(zz)).Add(w)
  1235. }
  1236. if sign {
  1237. y = y.Neg()
  1238. }
  1239. return y
  1240. }
  1241. var _tanP = [...]Decimal{
  1242. NewFromFloat(-1.30936939181383777646e+4), // 0xc0c992d8d24f3f38
  1243. NewFromFloat(1.15351664838587416140e+6), // 0x413199eca5fc9ddd
  1244. NewFromFloat(-1.79565251976484877988e+7), // 0xc1711fead3299176
  1245. }
  1246. var _tanQ = [...]Decimal{
  1247. NewFromFloat(1.00000000000000000000e+0),
  1248. NewFromFloat(1.36812963470692954678e+4), //0x40cab8a5eeb36572
  1249. NewFromFloat(-1.32089234440210967447e+6), //0xc13427bc582abc96
  1250. NewFromFloat(2.50083801823357915839e+7), //0x4177d98fc2ead8ef
  1251. NewFromFloat(-5.38695755929454629881e+7), //0xc189afe03cbe5a31
  1252. }
  1253. // Tan returns the tangent of the radian argument x.
  1254. func (d Decimal) Tan() Decimal {
  1255. PI4A := NewFromFloat(7.85398125648498535156e-1) // 0x3fe921fb40000000, Pi/4 split into three parts
  1256. PI4B := NewFromFloat(3.77489470793079817668e-8) // 0x3e64442d00000000,
  1257. PI4C := NewFromFloat(2.69515142907905952645e-15) // 0x3ce8469898cc5170,
  1258. M4PI := NewFromFloat(1.273239544735162542821171882678754627704620361328125) // 4/pi
  1259. if d.Equal(NewFromFloat(0.0)) {
  1260. return d
  1261. }
  1262. // make argument positive but save the sign
  1263. sign := false
  1264. if d.LessThan(NewFromFloat(0.0)) {
  1265. d = d.Neg()
  1266. sign = true
  1267. }
  1268. j := d.Mul(M4PI).IntPart() // integer part of x/(Pi/4), as integer for tests on the phase angle
  1269. y := NewFromFloat(float64(j)) // integer part of x/(Pi/4), as float
  1270. // map zeros to origin
  1271. if j&1 == 1 {
  1272. j++
  1273. y = y.Add(NewFromFloat(1.0))
  1274. }
  1275. z := d.Sub(y.Mul(PI4A)).Sub(y.Mul(PI4B)).Sub(y.Mul(PI4C)) // Extended precision modular arithmetic
  1276. zz := z.Mul(z)
  1277. if zz.GreaterThan(NewFromFloat(1e-14)) {
  1278. w := zz.Mul(_tanP[0].Mul(zz).Add(_tanP[1]).Mul(zz).Add(_tanP[2]))
  1279. x := zz.Add(_tanQ[1]).Mul(zz).Add(_tanQ[2]).Mul(zz).Add(_tanQ[3]).Mul(zz).Add(_tanQ[4])
  1280. y = z.Add(z.Mul(w.Div(x)))
  1281. } else {
  1282. y = z
  1283. }
  1284. if j&2 == 2 {
  1285. y = NewFromFloat(-1.0).Div(y)
  1286. }
  1287. if sign {
  1288. y = y.Neg()
  1289. }
  1290. return y
  1291. }