登录
首页 >  Golang >  Go问答

Go/Golang:如何从 big.Float 中提取最低有效数字?

来源:stackoverflow

时间:2024-03-16 18:18:31 288浏览 收藏

Go语言中,从`big.Float`类型变量中提取最低有效数字是一个性能挑战,尤其是当精度很高时。标准库中没有直接返回这些数字的函数,但可以通过计算它们来实现。一种有效的方法是分离出感兴趣的数字并打印它们,避免了为确定每个数字而进行大量计算。本文提供了一个示例代码,演示如何将`big.Float`中的特定数字移动到小数点右或左侧,然后截断为整数,以表示所需的数字。

问题内容

在 Go/Golang 中,我有一个 big.Float 类型的变量,其(任意)精度为 3,324,000,表示 1,000,000 位的十进制数。这是计算 pi 的迭代结果。 现在我想打印出最低有效的 100 位数字,即数字 999,900 到 1,000,000。

我尝试使用 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)
}

到这里,我们也就讲完了《Go/Golang:如何从 big.Float 中提取最低有效数字?》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>