我需要找到 big.Rat 的平方根。有沒有辦法在不損失(已經存在的)準確性的情況下做到這一點?
例如,我可以將分子和分母轉換為浮點數,得到平方根,然后將其轉換回來......
func ratSquareRoot(num *big.Rat) *big.Rat {
f, exact := num.Float64() //Yuck! Floats!
squareRoot := math.Sqrt(f)
var accuracy int64 = 10 ^ 15 //Significant digits of precision for float64
return big.NewRat(int64(squareRoot*float64(accuracy)), accuracy)
// ^ This is now totally worthless. And also probably not simplified very well.
}
...但這會消除使用理性的所有準確性。有沒有更好的方法來做到這一點?
uj5u.com熱心網友回復:
該big.Float型別有一個.Sqrt(x)操作,并處理明確定義您的目標精度。我會嘗試使用它并將結果轉換回 aRat在您的問題中具有相同的操作,僅操作big.Int值。
r := big.NewRat(1, 3)
var x big.Float
x.SetPrec(30) // I didn't figure out the 'Prec' part correctly, read the docs more carefully than I did and experiement
x.SetRat(r)
var s big.Float
s.SetPrec(15)
s.Sqrt(&x)
r, _ = s.Rat(nil)
fmt.Println(x.String(), s.String())
fmt.Println(r.String(), float64(18919)/float64(32768))
操場
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/412182.html
標籤:
