【问题标题】:The maximum value for float64 and complex128 type in GoGo中float64和complex128类型的最大值
【发布时间】:2020-12-18 05:23:44
【问题描述】:
我需要知道 golang 中 float64 和 complex128 变量类型的最大值。 go 似乎没有 float.h 的等价物,我不知道如何计算它。
【问题讨论】:
-
就像您提到的 C 头文件一样,在 Go 中,此信息可在包文档中找到。您可以在以下位置查看标准库包文档:golang.org/pkg 在您的特定情况下,您想探索数学包和内置包。您可以在常量部分下找到 MaxFloat64 的详细信息。对于 complex128,您可以阅读 complex128 声明上方的源注释以了解 complex128 可能的最大值。包文档还包含指向包源文件的链接(粗体蓝色超链接)。
标签:
variables
go
floating-point
【解决方案1】:
例如,
package main
import (
"fmt"
"math"
)
func main() {
const f = math.MaxFloat64
fmt.Printf("%[1]T %[1]v\n", f)
const c = complex(math.MaxFloat64, math.MaxFloat64)
fmt.Printf("%[1]T %[1]v\n", c)
}
输出:
float64 1.7976931348623157e+308
complex128 (1.7976931348623157e+308+1.7976931348623157e+308i)
Package math
import "math"
浮点限制值。 Max 是最大的有限值
可以用类型来表示。 SmallestNonzero 是最小的正数,
类型可表示的非零值。
const (
MaxFloat32 = 3.40282346638528859811704183484516925440e+38 // 2**127 * (2**24 - 1) / 2**23
SmallestNonzeroFloat32 = 1.401298464324817070923729583289916131280e-45 // 1 / 2**(127 - 1 + 23)
MaxFloat64 = 1.797693134862315708145274237317043567981e+308 // 2**1023 * (2**53 - 1) / 2**52
SmallestNonzeroFloat64 = 4.940656458412465441765687928682213723651e-324 // 1 / 2**(1023 - 1 + 52)
)
The Go Programming Language Specification
Numeric types
数字类型表示整数或浮点值的集合。
预先声明的独立于架构的数字类型是:
uint8 the set of all unsigned 8-bit integers (0 to 255)
uint16 the set of all unsigned 16-bit integers (0 to 65535)
uint32 the set of all unsigned 32-bit integers (0 to 4294967295)
uint64 the set of all unsigned 64-bit integers (0 to 18446744073709551615)
int8 the set of all signed 8-bit integers (-128 to 127)
int16 the set of all signed 16-bit integers (-32768 to 32767)
int32 the set of all signed 32-bit integers (-2147483648 to 2147483647)
int64 the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807)
float32 the set of all IEEE-754 32-bit floating-point numbers
float64 the set of all IEEE-754 64-bit floating-point numbers
complex64 the set of all complex numbers with float32 real and imaginary parts
complex128 the set of all complex numbers with float64 real and imaginary parts
byte alias for uint8
rune alias for int32
n 位整数的值是 n 位宽,用
二进制补码算法。
还有一组预先声明的数字类型
实现特定的大小:
uint either 32 or 64 bits
int same size as uint
uintptr an unsigned integer large enough to store the uninterpreted bits of a pointer value
为避免可移植性问题,所有数字类型都是不同的,除了
byte 是 uint8 的别名,rune 是 uint8 的别名
整数 32。不同数字类型混合时需要转换
在表达式或赋值中。例如, int32 和 int 不是
相同的类型,即使它们在特定的尺寸上可能具有相同的尺寸
架构。
【解决方案2】:
您也可以考虑使用math 包中的Inf 方法
返回一个无穷大的值(如果需要,可以为正或负),但被认为是float64。
不太确定math.MaxFloat64 和math.Inf() 之间是否存在争论。比较两者,我发现 Go 将无穷大值解释为大于最大浮点值。
package main
import (
"fmt"
"math"
)
func main() {
infPos := math.Inf(1) // gives positive infinity
fmt.Printf("%[1]T %[1]v\n", infPos)
infNeg := math.Inf(-1) // gives negative infinity
fmt.Printf("%[1]T %[1]v\n", infNeg)
}