在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)
}

Go相关问答推荐

如何模拟嵌入. FS?

Golang ==错误:OCI运行时创建失败:无法启动容器进程:exec:./" bin:stat./" bin:没有这样的文件或目录:未知

租户GUID X的租户不存在self 邮箱帐户的租户(我是唯一的成员)

Websocket服务器实现与x/net库trowing 403

JetBrains Goland,禁用突出显示测试文件

包裹网.Conn导致挂起读取

我可以扫描表中每个项目的最高范围键值吗?

为什么标准库中的 IsSorted 会反向迭代切片?

在 GoLang 中对自定义 struct 体数组进行排序

杜松子wine 和中间件

如何将 DirName 和 serial 添加到 X509v3 Authority Key Identifier

无法将 graphql-ws 连接到 gqlgen

如何将整数哈希细分为范围

go - 仅在函数即将返回错误时清理资源

如何 Select 前 N 个元素 Gin-Gorm

Golang Echo Labstack 如何在模板视图中调用函数/方法

httprouterhttp.HandlerFunc() 是如何工作的?

在 Go 中将指针传递给函数的正确方法是什么,以便我可以读取和/或修改指针表示的值?

在 Golang 中使用 OR 条件验证 struct 的两个字段

有没有一种方法可以确保传递的值具有使用泛型的某些字段?