我需要找到一个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.}
...but,这将消除使用rational的所有准确性。有更好的方法吗?
发布于 2022-01-15 17:12:30
big.Float类型有一个.Sqrt(x)操作,并处理明确定义目标精度的操作。我尝试使用该方法,并将结果转换为Rat,在您的问题中使用相同的操作,只操作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://stackoverflow.com/questions/70723547
复制相似问题