Golang float32 类型
最后修改时间 2025 年 5 月 8 日
本教程讲解如何在 Go 中使用 `float32` 内置类型。我们将通过算术运算的实际示例来涵盖浮点数基础知识。
`float32` 类型在 Go 中表示单精度浮点数。它占用 32 位(4 字节)内存,提供约 6-9 位十进制精度。
在 Go 中,`float32` 用于内存效率重要的计算。为了获得更高的精度,通常首选 `float64`。
基本的 float32 声明和初始化
使用 `float32` 最简单的方法是声明和初始化变量。此示例展示了基本的变量声明和算术运算。
注意:在 Go 中,浮点文字默认为 float64。
package main import "fmt" func main() { var f1 float32 = 3.14 f2 := float32(2.718) // Type conversion sum := f1 + f2 product := f1 * f2 fmt.Printf("Sum: %.3f, Product: %.3f\n", sum, product) fmt.Printf("Types: f1 %T, f2 %T\n", f1, f2) }
我们声明了两个 float32 变量并执行了基本算术运算。`%.3f` 格式说明符以 3 位小数打印。文字需要类型转换。
Float32 的精度和限制
与 float64 相比,Float32 的精度有限。此示例演示了对大数和小数的精度限制。
package main import "fmt" func main() { large := float32(123456789.0) small := float32(0.000000123456789) fmt.Println("Large number:", large) fmt.Println("Small number:", small) // Demonstrate precision loss a := float32(1.0000001) b := float32(1.0000002) fmt.Println("a == b?", a == b) // Might be true due to precision }
输出显示了 float32 如何在非常大或非常小的数字上丢失精度。相等性比较演示了计算中潜在的精度问题。
使用 float32 进行数学运算
Float32 支持所有标准数学运算。此示例展示了各种运算,包括 math 包中的运算。
package main import ( "fmt" "math" ) func main() { x := float32(9.0) y := float32(4.0) // Basic operations fmt.Println("x + y =", x+y) fmt.Println("x - y =", x-y) fmt.Println("x * y =", x*y) fmt.Println("x / y =", x/y) // Math functions require type conversion fmt.Println("Sqrt(x) =", float32(math.Sqrt(float64(x)))) fmt.Println("Pow(x, y) =", float32(math.Pow(float64(x), float64(y)))) }
基本算术可以直接与 float32 一起使用,但数学函数需要转换为 float64。这显示了精度和内存之间的权衡。
比较 float32 值
由于精度问题,比较浮点数需要格外小心。此示例演示了正确的比较技术。
package main import ( "fmt" "math" ) const epsilon = 1e-6 // Small threshold for comparison func main() { a := float32(0.1) b := float32(0.2) c := float32(0.3) // Problematic direct comparison fmt.Println("a + b == c?", a+b == c) // Better approach using epsilon sum := a + b diff := float32(math.Abs(float64(sum - c))) fmt.Println("Approximately equal?", diff < epsilon) // Special values nan := float32(math.NaN()) inf := float32(math.Inf(1)) fmt.Println("Is NaN?", math.IsNaN(float64(nan))) fmt.Println("Is Inf?", math.IsInf(float64(inf), 1)) }
由于舍入误差,直接相等性比较通常会失败。使用 epsilon 阈值更可靠。该示例还展示了特殊值的处理。
数组和切片中的 Float32
Float32 通常用于集合中以提高内存效率。此示例演示了具有常见运算的 float32 数组和切片。
package main import "fmt" func main() { // Array of float32 temps := [5]float32{21.5, 22.1, 23.8, 24.2, 25.0} // Slice of float32 readings := []float32{98.6, 99.2, 100.1, 101.3} // Calculate average var sum float32 for _, temp := range temps { sum += temp } avg := sum / float32(len(temps)) fmt.Printf("Average temp: %.1f°C\n", avg) // Append to slice readings = append(readings, 102.0, 103.5) fmt.Println("Updated readings:", readings) // Multi-dimensional matrix := [2][2]float32{{1.2, 3.4}, {5.6, 7.8}} fmt.Println("Matrix:", matrix) }
Float32 数组和切片与其他类型的工作方式类似。该示例展示了迭代、追加和多维用法。Float32 常用于数值计算。
来源
本教程通过算术运算、比较和集合用法的实际示例,涵盖了 Go 中的 `float32` 类型。