登录
首页 >  Golang >  Go问答

Go 如何对常量进行算术运算?

来源:stackoverflow

时间:2024-04-28 14:33:37 190浏览 收藏

来到golang学习网的大家,相信都是编程学习爱好者,希望在这里学习Golang相关编程知识。下面本篇文章就来带大家聊聊《Go 如何对常量进行算术运算?》,介绍一下,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

我一直在阅读这篇关于 go 中常量的文章,我试图了解它们如何在内存中存储和使用。您可以在 go 中对非常大的常量执行操作,只要结果适合内存,您就可以将该结果强制为某种类型。例如,此代码打印 10,如您所料:

const Huge = 1e1000
fmt.Println(Huge / 1e999)

这在幕后是如何工作的?在某些时候,go 必须将 1e10001e999 存储在内存中,以便对它们执行操作。那么常量是如何存储的,go 又是如何对它们进行运算的呢?


正确答案


简短摘要(tl;dr)位于答案的末尾。

无类型的任意精度常量在运行时不存在,常量仅在编译时(编译期间)存在。话虽这么说,go 不必在运行时以任意精度表示常量,只需在编译应用程序时即可。

为什么?因为常量不会被编译到可执行二进制文件中。他们不一定是这样。让我们以您的例子为例:
const huge = 1e1000
fmt.println(huge / 1e999)

源代码中有一个常量 huge (并且将位于包对象中),但它不会出现在您的可执行文件中。相反,对 fmt.println() 的函数调用将被记录并传递给它的值,其类型为 float64。因此,在可执行文件中,只会记录 float6410.0。可执行文件中没有任何迹象表明任何数字为 1e1000

float64 类型派生自非类型化常量 huge默认类型。 1e1000floating-point literal。要验证它:

const huge = 1e1000
x := huge / 1e999
fmt.printf("%t", x) // prints float64

返回任意精度:

Spec: Constants:

数字常量表示任意精度的精确值并且不会溢出。

因此常量表示任意精度的精确值。正如我们所看到的,不需要在运行时以任意精度表示常量,但编译器仍然必须在编译时做一些事情。确实如此!

显然无法处理“无限”精度。但没有必要,因为源代码本身并不是“无限的”(源代码的大小是有限的)。尽管如此,允许真正任意的精度是不切实际的。因此,规范在这方面为编译器提供了一些自由:

实现限制:尽管数字常量在语言中具有任意精度,但编译器可以使用精度有限的内部表示来实现它们。也就是说,每个实现都必须:

  • 表示至少 256 位的整数常量。
  • 表示浮点常量,包括复数常量的各个部分,尾数至少为 256 位,带符号指数至少为 32 位。
  • 如果无法精确表示整数常量,则给出错误。
  • 如果由于溢出而无法表示浮点或复数常量,则给出错误。
  • 如果由于精度限制而无法表示浮点或复数常量,则舍入到最接近的可表示常量。 这些要求既适用于文字常量,也适用于计算 constant expressions 的结果。

但是,还要注意,当上述所有内容发生时,标准包为您提供了仍然以“任意”精度表示和处理值(常量)的方法,请参阅包 go/constant。您可以查看其源代码以获取了解它是如何实现的。

实现在 go/constant/value.go 中。代表此类值的类型:

// a value represents the value of a go constant.
type value interface {
    // kind returns the value kind.
    kind() kind

    // string returns a short, human-readable form of the value.
    // for numeric values, the result may be an approximation;
    // for string values the result may be a shortened string.
    // use exactstring for a string representing a value exactly.
    string() string

    // exactstring returns an exact, printable form of the value.
    exactstring() string

    // prevent external implementations.
    implementsvalue()
}

type (
    unknownval struct{}
    boolval    bool
    stringval  string
    int64val   int64                    // int values representable as an int64
    intval     struct{ val *big.int }   // int values not representable as an int64
    ratval     struct{ val *big.rat }   // float values representable as a fraction
    floatval   struct{ val *big.float } // float values not representable as a fraction
    complexval struct{ re, im value }
)

如您所见,math/big 包用于表示无类型的任意精度值。例如 big.Int(来自 math/big/int.go):

// an int represents a signed multi-precision integer.
// the zero value for an int represents the value 0.
type int struct {
    neg bool // sign
    abs nat  // absolute value of the integer
}

nat 所在位置(来自 math/big/nat.go):

// an unsigned integer x of the form
//
//   x = x[n-1]*_b^(n-1) + x[n-2]*_b^(n-2) + ... + x[1]*_b + x[0]
//
// with 0 <= x[i] < _b and 0 <= i < n is stored in a slice of length n,
// with the digits x[i] as the slice elements.
//
// a number is normalized if the slice contains no leading 0 digits.
// during arithmetic operations, denormalized values may occur but are
// always normalized before returning the final result. the normalized
// representation of 0 is the empty or nil slice (length = 0).
//
type nat []word

最后是 Word(来自 math/big/arith.go

// a word represents a single digit of a multi-precision unsigned integer.
type word uintptr

摘要

在运行时:预定义类型提供有限的精度,但您可以使用某些包“模拟”任意精度,例如 math/biggo/constant。在编译时:常量看似提供任意精度,但实际上编译器可能无法达到这一点(不必);但规范仍然为所有编译器必须支持的常量提供了最低精度,例如整数常量必须用至少 256 位表示,即 32 字节(与 int64 相比,“仅”8 字节)。

创建可执行二进制文件时,必须转换常量表达式(具有任意精度)的结果并用有限精度类型的值表示 - 这可能是不可能的,因此可能会导致编译时错误。请注意,只有结果(而不是中间操作数)需要转换为有限精度,常量运算可以任意精度执行。

规范中没有定义如何实现这种任意或增强的精度,例如 math/big 将数字的“数字”存储在切片中(其中数字不是以 10 为基数表示的数字,而是“数字”)是一个 uintptr ,类似于 32 位架构上的基本 4294967295 表示,在 64 位架构上甚至更大)。

go 常量不会分配到内存。它们由编译器在上下文中使用。您引用的博客文章给出了 pi 的示例:

Pi    = 3.14159265358979323846264338327950288419716939937510582097494459

理论要掌握,实操不能落!以上关于《Go 如何对常量进行算术运算?》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

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