golang基础数据类型-浮点型


本文摘自网络,作者,侵删。

go语言提供了两种精度的浮点数,float32和float64

// float32 is the set of all IEEE-754 32-bit floating-point numbers.
type float32 float32

// float64 is the set of all IEEE-754 64-bit floating-point numbers.
type float64 float64

零值和默认类型

func TestFloat(t *testing.T) {
   // 零值0
   var f1 float64
   fmt.Println(f1) // 0
    
   // 默认类型
   f2 := 3.14
   fmt.Println(reflect.TypeOf(f2), f2) // float64 3.14
}

表现形式

func TestFloat(t *testing.T) {
   // 省略小数点后面的数
   f1 := 3.
   // 省略小数点前面的数
   f2 := .14
   // 科学计数法,大写E和小写e都支持
   // 等价于5.1234 * 100
   f3 := 5.1234e2
   // 等价于5.1234 / 100
   f4 := 5.1234e-2
   fmt.Println(f1, f2, f3, f4) // 3 0.14 512.34 0.051234
}

如何选择

一个float32类型的浮点数可以提供大约6个十进制数的精度,而float64则可以提供约15个十进制数的精度;通常应该优先使用float64类型,因为float32类型的累计计算误差很容易扩散,并且float32能精确表示的正整数并不是很大

备注:因为float32的有效bit位只有23个,其它的bit位用于指数和符号;当整数大于23bit能表达的范围时,float32的表示将出现误差

func TestFloat(t *testing.T) {
   var f float32 = 1 << 24
   fmt.Println(f == f+1) // true
}

边界值

math包里面

// Floating-point limit values.
// Max is the largest finite value representable by the type.
// SmallestNonzero is the smallest positive, non-zero value representable by the type.
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)
)

本文来自:简书

感谢作者:大白能_3db0

查看原文:golang基础数据类型-浮点型

相关阅读 >>

手撸Golang 基本数据结构与算法 哈希表

Golang怎么执行cmd命令行

debounce function(防抖函数) for Golang

Go语言循环语句

Golang中的切片与gc

非docker部署fabric2.2.0网络

[系列] Go - 学习 grpc.dial(target string, opts …dialoption) 的写法

Golang二维切片初始化

tidb-lite: 用于 Golang 数据库相关代码的单元测试

Gocn酷Go推荐】网络流量抓包库 Gopacket介绍

更多相关阅读请进入《Go》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...