新聞中心
實(shí)際開(kāi)發(fā)中,對(duì)于超出 int64 或者 uint64 類型的大數(shù)進(jìn)行計(jì)算時(shí),如果對(duì)精度沒(méi)有要求,使用 float32 或者 float64 就可以勝任,但如果對(duì)精度有嚴(yán)格要求的時(shí)候,我們就不能使用浮點(diǎn)數(shù)了,因?yàn)楦↑c(diǎn)數(shù)在內(nèi)存中只能被近似的表示。

Go語(yǔ)言中 math/big 包實(shí)現(xiàn)了大數(shù)字的多精度計(jì)算,支持 Int(有符號(hào)整數(shù))、Rat(有理數(shù))和 Float(浮點(diǎn)數(shù))等數(shù)字類型。
這些類型可以實(shí)現(xiàn)任意位數(shù)的數(shù)字,只要內(nèi)存足夠大,但缺點(diǎn)是需要更大的內(nèi)存和處理開(kāi)銷,這使得它們使用起來(lái)要比內(nèi)置的數(shù)字類型慢很多。
在 math/big 包中,Int 類型定義如下所示:
// An Int represents a signed multi-precision integer.
// The zero value for an Int represents the value 0.
type Int struct {
neg bool // sign
abs nat // absolute value of the integer
} 生成 Int 類型的方法為 NewInt(),如下所示:
// NewInt allocates and returns a new Int set to x.
func NewInt(x int64) *Int {
return new(Int).SetInt64(x)
}注意:NewInt() 函數(shù)只對(duì) int64 有效,其他類型必須先轉(zhuǎn)成 int64 才行。
Go語(yǔ)言中還提供了許多 Set 函數(shù),可以方便的把其他類型的整形存入 Int ,因此,我們可以先 new(int) 然后再調(diào)用 Set 函數(shù),Set 函數(shù)有如下幾種:
// SetInt64 函數(shù)將 z 轉(zhuǎn)換為 x 并返回 z。
func (z *Int) SetInt64(x int64) *Int {
neg := false
if x < 0 {
neg = true
x = -x
}
z.abs = z.abs.setUint64(uint64(x))
z.neg = neg
return z
}
?
// SetUint64 函數(shù)將 z 轉(zhuǎn)換為 x 并返回 z。
func (z *Int) SetUint64(x uint64) *Int {
z.abs = z.abs.setUint64(x)
z.neg = false
return z
}
?
// Set 函數(shù)將 z 轉(zhuǎn)換為 x 并返回 z。
func (z *Int) Set(x *Int) *Int {
if z != x {
z.abs = z.abs.set(x.abs)
z.neg = x.neg
}
return z
} 示例代碼如下所示:
package main
import (
"fmt"
"math/big"
)
func main() {
big1 := new(big.Int).SetUint64(uint64(1000))
fmt.Println("big1 is: ", big1)
big2 := big1.Uint64()
fmt.Println("big2 is: ", big2)
}運(yùn)行結(jié)果如下:
big1 is: 1000
big2 is: 1000
除了上述的 Set 函數(shù),math/big 包中還提供了一個(gè) SetString() 函數(shù),可以指定進(jìn)制數(shù),比如二進(jìn)制、十進(jìn)制或者十六進(jìn)制等!
// SetString sets z to the value of s, interpreted in the given base,
// and returns z and a boolean indicating success. The entire string
// (not just a prefix) must be valid for success. If SetString fails,
// the value of z is undefined but the returned value is nil.
//
// The base argument must be 0 or a value between 2 and MaxBase. If the base
// is 0, the string prefix determines the actual conversion base. A prefix of
// ``0x'' or ``0X'' selects base 16; the ``0'' prefix selects base 8, and a
// ``0b'' or ``0B'' prefix selects base 2. Otherwise the selected base is 10.
//
func (z *Int) SetString(s string, base int) (*Int, bool) {
r := strings.NewReader(s)
if _, _, err := z.scan(r, base); err != nil {
return nil, false
}
// entire string must have been consumed
if _, err := r.ReadByte(); err != io.EOF {
return nil, false
}
return z, true // err == io.EOF => scan consumed all of s
} 示例代碼如下所示:
package main
import (
"fmt"
"math/big"
)
func main() {
big1, _ := new(big.Int).SetString("1000", 10)
fmt.Println("big1 is: ", big1)
big2 := big1.Uint64()
fmt.Println("big2 is: ", big2)
}運(yùn)行結(jié)果如下:
big1 is: 1000
big2 is: 1000
因?yàn)镚o語(yǔ)言不支持運(yùn)算符重載,所以所有大數(shù)字類型都有像是 Add() 和 Mul() 這樣的方法。
Add 方法的定義如下所示:
func (z *Int) Add(x, y *Int) *Int
該方法會(huì)將 z 轉(zhuǎn)換為 x + y 并返回 z。
【示例】計(jì)算第 1000 位的斐波那契數(shù)列。
package main
import (
"fmt"
"math/big"
"time"
)
const LIM = 1000 //求第1000位的斐波那契數(shù)列
var fibs [LIM]*big.Int //使用數(shù)組保存計(jì)算出來(lái)的數(shù)列的指針
func main() {
result := big.NewInt(0)
start := time.Now()
for i := 0; i < LIM; i++ {
result = fibonacci(i)
fmt.Printf("數(shù)列第 %d 位: %d\n", i+1, result)
}
end := time.Now()
delta := end.Sub(start)
fmt.Printf("執(zhí)行完成,所耗時(shí)間為: %s\n", delta)
}
func fibonacci(n int) (res *big.Int) {
if n <= 1 {
res = big.NewInt(1)
} else {
temp := new(big.Int)
res = temp.Add(fibs[n-1], fibs[n-2])
}
fibs[n] = res
return
}運(yùn)行結(jié)果如下:
數(shù)列第 1 位: 1
數(shù)列第 2 位: 1
數(shù)列第 3 位: 2
數(shù)列第 4 位: 3
數(shù)列第 5 位: 5
...
數(shù)列第 997 位: 10261062362033262336604926729245222132668558120602124277764622905699407982546711488272859468887457959
08773311924256407785074365766118082732679853917775891982813511440749936979646564952426675539110499009
9120377
數(shù)列第 998 位: 16602747662452097049541800472897701834948051198384828062358553091918573717701170201065510185595898605
10409473691887927846223301598102952299783631123261876053919903676539979992673143323971886037334508837
5054249
數(shù)列第 999 位: 26863810024485359386146727202142923967616609318986952340123175997617981700247881689338369654483356564
19182785616144335631297667364221035032463485041037768036733415117289916972319708276398561576445007847
4174626
數(shù)列第 1000 位: 4346655768693745643568852767504062580256466051737178040248172908953655541794905189040387984007925516
92959225930803226347752096896232398733224711616429964409065331879382989696499285160037044761377951668
49228875
執(zhí)行完成,所耗時(shí)間為: 6.945ms
本文標(biāo)題:創(chuàng)新互聯(lián)GO教程:Go語(yǔ)言big包:對(duì)整數(shù)的高精度計(jì)算
轉(zhuǎn)載來(lái)于:http://m.fisionsoft.com.cn/article/dpehioe.html


咨詢
建站咨詢
