在Go/Golang中,我有一个类型为big的变量.浮点数的(任意)精度为3324000,表示100万位的十进制数.这是计算pi的迭代结果.
我try 使用fmt将变量转换为字符串.Sprintf()和big.Text().然而,这两个函数都会消耗大量的处理时间,当进一步提高精度时,这是不可接受的(很多小时甚至几天).
我正在搜索一些提取变量最后100位(十进制)的函数.
在Go/Golang中,我有一个类型为big的变量.浮点数的(任意)精度为3324000,表示100万位的十进制数.这是计算pi的迭代结果.
我try 使用fmt将变量转换为字符串.Sprintf()和big.Text().然而,这两个函数都会消耗大量的处理时间,当进一步提高精度时,这是不可接受的(很多小时甚至几天).
我正在搜索一些提取变量最后100位(十进制)的函数.
标准库不提供有效返回这些数字的函数,但您可以计算它们.
隔离感兴趣的数字并打印出来更有效.这避免了为确定每个数字而进行的大量计算.
下面的代码显示了一种方法.您需要确保有足够的精度来准确地生成它们.
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)
}