加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

for循环 – 带浮点数的GoLang for循环创建错误

发布时间:2020-12-16 09:25:22 所属栏目:大数据 来源:网络整理
导读:有人可以解释以下内容.我有一个函数在go中接受一些float64,然后使用这个值来计算很多其他值.功能看起来像 func (g *Geometry) CalcStresses(x,zmax,zmin float64)(Vertical) 将结果放入类似的结构中 type Vertical struct { X float64 Stresses []Stress} 现
有人可以解释以下内容.我有一个函数在go中接受一些float64,然后使用这个值来计算很多其他值.功能看起来像

func (g *Geometry) CalcStresses(x,zmax,zmin float64)(Vertical)

将结果放入类似的结构中

type Vertical struct {
    X float64
    Stresses []Stress
}

现在有趣的是这个.如果我这样调用这个函数;

for i:=14.0; i<15.0; i+=0.1{
    result := geo.CalcStresses(i,10,-10)
}

那么我得到很多结果,其中Stress数组是空的,另外有趣的细节是x有时显示像一个有??很多小数的数字(如14.3999999999999999998)

但是,如果我这样调用这个函数;

for i:=0; i<10; i++{
    x := 14.0 + float64(i) * 0.1
    result := geo.CalcStresses(x,-10)
}

一切都很好.

有谁知道为什么会这样?

提前致谢,

解决方法

并非所有实数都可以用二进制浮点格式精确表示,因此循环浮点数会产生麻烦.

来自维基百科Floating point

The fact that floating-point numbers cannot precisely represent all real numbers,and that floating-point operations cannot precisely represent true arithmetic operations,leads to many surprising situations. This is related to the finite precision with which computers generally represent numbers.

For example,the non-representability of 0.1 and 0.01 (in binary) means that the result of attempting to square 0.1 is neither 0.01 nor the representable number closest to it.

This code

for i := 14.0; i < 15.0; i += 0.1 {
    fmt.Println(i)
}

产生这个

14
14.1
14.2
14.299999999999999
14.399999999999999
14.499999999999998
14.599999999999998
14.699999999999998
14.799999999999997
14.899999999999997
14.999999999999996

您可以使用math.big.Rat类型准确表示有理数.

Example

x := big.NewRat(14,1)
y := big.NewRat(15,1)
z := big.NewRat(1,10)

for i := x; i.Cmp(y) < 0; i = i.Add(i,z) {
    v,_ := i.Float64()
    fmt.Println(v)
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读