首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Go/Golang:如何从big.Float中提取最小有效数字?

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

Stack Overflow用户
提问于 2022-04-02 09:44:09
回答 1查看 553关注 0票数 3

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

我尝试使用fmt.Sprintf()和big.Text()将变量转换为字符串。但是,这两个函数在进一步提高精度时都会消耗大量的处理时间,这是不可接受的(许多小时甚至几天)。

我正在搜索一些函数,这些函数提取变量的最后100位(十进制)数字。提前感谢您的支持。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-04-03 13:17:12

标准库没有提供一个函数来高效地返回这些数字,但是您可以计算它们。

分离您感兴趣的数字并打印它们更有效。这样就避免了计算过大的数字来确定每一个数字。

下面的代码显示了一种可以实现的方法。您将需要确保您有足够的精度来准确地生成它们。

代码语言:javascript
运行
复制
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)
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71716447

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档