英文:
Easiest way to get the machine epsilon in Go
问题
获取Go语言中机器epsilon的最简单方法是什么?其他浮点数方面的内容,如精度、最小指数、最大指数、抖动等呢?
我知道有一个math/const包,其中包含不同浮点类型的最大值和最小值(http://golang.org/src/pkg/math/const.go),但没有其他信息。
我想知道的一个原因是为了验证我是否已经达到了机器可以进行的给定计算的最大精度,以便我不会过早退出或尝试时间过长。
另一个原因只是出于好奇。
谢谢
编辑:
为了好玩,我查了一下学校的一些笔记,看看如何手动计算epsilon,这是一个从C++翻译过来的粗略版本,http://play.golang.org/p/XOXwIdNfsa,希望你喜欢。
编辑:
下面是来自下方评论的内容(感谢提供了一种更符合习惯的查找epsilon的方法):
使用epsilon := math.Nextafter(1, 2) - 1
Playground – Nick Craig-Wood Mar 5 at 8:07
英文:
What is the easiest way to get the machine epsilon in Go? What about other aspects of floating point numbers such as precision, min exponent, max exponent, wobble, etc?
I realize that there is the math/const package with the max and min for the different float types (http://golang.org/src/pkg/math/const.go), but no other information.
One reason I would like to know is to verify that I've reached the maximum precision for a given calculation that the machine can do so that I don't quit to early or try longer then needed.
The other is just for curiosity.
Thanks
EDIT:
For the fun I looked up in some notes from school on how to calculate the epsilon manually for fun and here is a rough translation from c++ http://play.golang.org/p/XOXwIdNfsa enjoy
EDIT:
comment from below (thanks for a more idiomatic way of finding epsilon):
Use epsilon := math.Nextafter(1, 2) - 1
Playground – Nick Craig-Wood Mar 5 at 8:07
答案1
得分: 15
这是要翻译的内容:
这个问题没有被定义,我在问题跟踪器上找到了一个解决方案,解决方案是“按预期工作”:
https://code.google.com/p/go/issues/detail?id=966
建议是如果需要,可以使用math.Nextafter
来计算这个值。
具体来说,公式是math.Nextafter(1.0,2.0)-1.0
(第二个参数可以是大于1.0的任意数字)。
英文:
It's not defined, I found the issue resolved as "working as intended" on the issue tracker:
https://code.google.com/p/go/issues/detail?id=966
The suggestion seems to be to use math.Nextafter
to derive the value if you need it.
Specifically, the formula is math.Nextafter(1.0,2.0)-1.0
(the second argument can be any number greater than 1.0).
答案2
得分: 2
上述代码适用于任何二进制浮点类型(例如你提到的Go类型)。
package main
import "fmt"
func main() {
f32 := float32(7.)/3 - float32(4.)/3 - float32(1.)
fmt.Println(f32)
f64 := float64(7.)/3 - float64(4.)/3 - float64(1.)
fmt.Println(f64)
}
输出结果为:
-1.1920929e-07
2.220446049250313e-16
对f32取绝对值可以得到正确的机器ε。
编辑: 如SGJ在下面的评论中提到的,这在十进制浮点类型上不起作用,但据我所知,Go语言尚未实现这些类型。
英文:
The above works for any binary floating point type (e.g. the Go types you are referring to.)
package main
import "fmt"
func main() {
f32 := float32(7.)/3 - float32(4.)/3 - float32(1.)
fmt.Println(f32)
f64 := float64(7.)/3 - float64(4.)/3 - float64(1.)
fmt.Println(f64)
}
gives:
-1.1920929e-07
2.220446049250313e-16
taking the absolute (unsigned) value of f32 yields the correct machine ε.
Edit: As mentioned below in a comment from SGJ, this would not work on decimal floating point types, but as far as I'm aware they have not been implemented yet in Golang.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论