草庐IT

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

coder 2023-06-28 原文

我一直在读这个post on constants in 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。因此,在可执行文件中,只会记录 float64 值为 10.0 的值。可执行文件中没有任何数字为 1e1000 的迹象。

float64 类型派生自untyped 常量Huge默认 类型。 1e1000floating-point literal .验证它:

const Huge = 1e1000
x := Huge / 1e999
fmt.Printf("%T", x) // Prints float64

回到任意精度:

Spec: Constants:

Numeric constants represent exact values of arbitrary precision and do not overflow.

所以常量表示任意精度的精确值。正如我们所见,没有必要在运行时 以任意精度表示常量,但编译器仍然需要在编译时 做一些事情。它确实!

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

Implementation restriction: Although numeric constants have arbitrary precision in the language, a compiler may implement them using an internal representation with limited precision. That said, every implementation must:

  • Represent integer constants with at least 256 bits.
  • Represent floating-point constants, including the parts of a complex constant, with a mantissa of at least 256 bits and a signed exponent of at least 32 bits.
  • Give an error if unable to represent an integer constant precisely.
  • Give an error if unable to represent a floating-point or complex constant due to overflow.
  • Round to the nearest representable constant if unable to represent a floating-point or complex constant due to limits on precision. These requirements apply both to literal constants and to the result of evaluating 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 字节(与“仅”8 字节的 int64 相比)。

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

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

关于go - Go 如何对常量进行算术运算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38982278/

有关go - Go 如何对常量进行算术运算?的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  4. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  5. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  6. ruby-on-rails - 按天对 Mongoid 对象进行分组 - 2

    在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev

  7. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  8. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  9. ruby-on-rails - 未初始化的常量 Psych::Syck (NameError) - 2

    在我的gem中,我需要yaml并且在我的本地计算机上运行良好。但是在将我的gem推送到ruby​​gems.org之后,当我尝试使用我的gem时,我收到一条错误消息=>"uninitializedconstantPsych::Syck(NameError)"谁能帮我解决这个问题?附言RubyVersion=>ruby1.9.2,GemVersion=>1.6.2,Bundlerversion=>1.0.15 最佳答案 经过几个小时的研究,我发现=>“YAML使用未维护的Syck库,而Psych使用现代的LibYAML”因此,为了解决

  10. ruby - 如何指定 Rack 处理程序 - 2

    Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack

随机推荐