在Go/Golang中,我有一个big.Float类型的变量,其(任意)精度为3,324,000,000,000表示小数位数1,000,000位。这是计算pi的迭代结果。现在我要打印出最不重要的100位数字,即999,900到1,000,000位数字。
我尝试使用fmt.Sprintf()和big.Text()将变量转换为字符串。但是,这两个函数在进一步提高精度时都会消耗大量的处理时间,这是不可接受的(许多小时甚至几天)。
我正在搜索一些函数,这些函数提取变量的最后100位(十进制)数字。提前感谢您的支持。
发布于 2022-04-03 13:17:12
标准库没有提供一个函数来高效地返回这些数字,但是您可以计算它们。
分离您感兴趣的数字并打印它们更有效。这样就避免了计算过大的数字来确定每一个数字。
下面的代码显示了一种可以实现的方法。您将需要确保您有足够的精度来准确地生成它们。
package main
import (
"fmt"
"math"
"math/big"
)
func main() {
// Replace with larger calculation.
pi := big.NewFloat(math.Pi)
const (
// Pi: 3.1415926535897932...
// Output: 5926535897
digitOffset = 3
digitLength = 10
)
// Move the desired digits to the right side of the decimal point.
mult := pow(10, digitOffset)
digits := new(big.Float).Mul(pi, mult)
// Remove the integer component.
digits.Sub(digits, trunc(digits))
// Move the digits to the left of the decimal point, and truncate
// to an integer representing the desired digits.
// This avoids undesirable rounding if you simply print the N
// digits after the decimal point.
mult = pow(10, digitLength)
digits.Mul(digits, mult)
digits = trunc(digits)
// Display the next 'digitLength' digits. Zero padded.
fmt.Printf("%0*.0f\n", digitLength, digits)
}
// trunc returns the integer component.
func trunc(n *big.Float) *big.Float {
intPart, accuracy := n.Int(nil)
_ = accuracy
return new(big.Float).SetInt(intPart)
}
// pow calculates n^idx.
func pow(n, idx int64) *big.Float {
if idx < 0 {
panic("invalid negative exponent")
}
result := new(big.Int).Exp(big.NewInt(n), big.NewInt(idx), nil)
return new(big.Float).SetInt(result)
}
https://stackoverflow.com/questions/71716447
复制相似问题