Golang float64 类型
最后修改时间 2025 年 5 月 8 日
本教程将解释如何在 Go 中使用 float64
内置类型。我们将通过实际的数值计算示例来介绍浮点数基础知识。
float64
类型代表 Go 中的 64 位浮点数。它提供约 15 位十进制精度,是浮点数字面量的默认类型。Float64 适用于大多数数值计算。
在 Go 中,float64
实现 IEEE 754 浮点数运算标准。它可以表示大约 1.7E-308 到 1.7E+308 范围内的值。像 NaN 和 Inf 这样的特殊值也受支持。
基本的 float64 声明和初始化
使用 float64 的最简单方法是通过显式类型声明变量。此示例显示了 float64 变量的基本声明和初始化。
package main import "fmt" func main() { var pi float64 = 3.141592653589793 var e = 2.718281828459045 // Type inferred as float64 fmt.Printf("pi: %v, type: %T\n", pi, pi) fmt.Printf("e: %v, type: %T\n", e, e) // Scientific notation avogadro := 6.02214076e23 fmt.Println("Avogadro's number:", avogadro) }
示例展示了创建 float64 变量的三种方式。第三种使用了科学计数法。所有没有后缀的浮点数字面量都是 float64。
Float64 算术运算
Float64 支持所有基本的算术运算。此示例演示了加法、减法、乘法、除法和取模运算。
package main import "fmt" func main() { a := 12.5 b := 3.2 fmt.Println("Addition:", a + b) fmt.Println("Subtraction:", a - b) fmt.Println("Multiplication:", a * b) fmt.Println("Division:", a / b) // Modulus using math.Mod fmt.Println("Modulus:", math.Mod(a, b)) // Compound assignment a += b fmt.Println("After +=:", a) }
示例展示了 float64 的基本算术运算。请注意,取模运算需要使用 math.Mod 函数。复合赋值运算符按预期工作。
比较 float64 值
由于精度问题,比较浮点数需要特别小心。此示例演示了 float64 值的安全比较技术。
package main import ( "fmt" "math" ) func main() { a := 0.1 + 0.2 b := 0.3 // Naive comparison (may fail) fmt.Println("Naive comparison:", a == b) // Safe comparison with tolerance tolerance := 1e-10 diff := math.Abs(a - b) fmt.Println("Safe comparison:", diff < tolerance) // Special values comparison nan := math.NaN() inf := math.Inf(1) fmt.Println("NaN == NaN:", nan == nan) // Always false fmt.Println("Is Inf:", math.IsInf(inf, 1)) }
示例展示了为什么直接相等比较通常在 float64 中会失败。它演示了使用容差值进行正确比较以及如何处理 NaN 和 Inf 等特殊值。
使用 float64 的数学函数
Go 的 math 包提供了许多操作 float64 的函数。此示例展示了标准库中可用的常见数学运算。
package main import ( "fmt" "math" ) func main() { x := 2.0 y := 3.0 fmt.Println("Square root:", math.Sqrt(x)) fmt.Println("Power:", math.Pow(x, y)) fmt.Println("Exponential:", math.Exp(x)) fmt.Println("Natural log:", math.Log(x)) fmt.Println("Sine:", math.Sin(math.Pi/x)) // Rounding functions fmt.Println("Ceil:", math.Ceil(3.14)) fmt.Println("Floor:", math.Floor(3.14)) fmt.Println("Round:", math.Round(3.14)) }
math 包为 float64 运算提供了全面的支持。这包括基本算术、三角函数、对数和舍入函数。所有数学函数都使用 float64 参数并返回值。
Float64 精度和格式化
格式化 float64 值需要理解其精度限制。此示例演示了 float64 输出的不同格式化选项。
package main import "fmt" func main() { value := 123.45678901234567 // Default formatting fmt.Println("Default:", value) // Precision control fmt.Printf("2 decimal places: %.2f\n", value) fmt.Printf("Scientific notation: %e\n", value) fmt.Printf("Large exponent: %g\n", value*1e30) // String formatting options fmt.Printf("Width 10, precision 4: %10.4f\n", value) fmt.Printf("Left aligned: %-10.2f|\n", value) }
示例展示了格式化 float64 值的各种方法。printf 动词 %f、%e 和 %g 提供了不同的格式化样式。可以控制精度和宽度以获得更好的输出呈现。
来源
本教程通过实际的数值计算和格式化示例,介绍了 Go 中的 float64
类型。