douhuan1905 2016-08-23 10:04
浏览 11
已采纳

去,循环和中断,无限循环

there is no error in the following code.

package main

import (
    "fmt"
    "math"
)

type ErrNegativeSqrt float64

func (e ErrNegativeSqrt) Error() string {
    return fmt.Sprintf("cannot Sqrt negative number: %v", float64(e))
}

func Sqrt(x float64) (float64, error) {
    if x < 0 {
        err := ErrNegativeSqrt(x)
        return x, err
    }
    z := x
    var delta = 1e-10
    for {
        n := z - (z*z - x) / (2*z)
        if math.Abs(n - z) < delta {
            break
        }
        z = n
    }
    return z, nil
}

func main() {
    fmt.Println(Sqrt(2))
    fmt.Println(Sqrt(-3))
}

But when I change the for loop in func Sqrt(), it led to infinite loop?

func Sqrt(x float64) (float64, error) {
    if x < 0 {
        err := ErrNegativeSqrt(x)
        return x, err
    }
    z := x
    var delta = 1e-10
    for {
        n := z - (z*z - x) / (2*z)
        if math.Abs(n - z) < delta {
            z = n // here ....
            break // break here
        }
    }
    return z, nil
}

Why there are different?

  • 写回答

1条回答 默认 最新

  • dongziduo9762 2016-08-23 10:14
    关注

    The second loop will be infinite since the logic is flawed. In this code:

    for {
        n := z - (z*z - x) / (2*z)
        if math.Abs(n - z) < delta {
            z = n // here ....
            break // break here
        }
    }
    

    value of z never updates to the newly calculated value. This results in n := z - (z*z - x) / (2*z) always working on the same z, that is equal to x, since the condition math.Abs(n - z) < delta never gets to be true.

    You need to assign to z again so it gets updated. You can check this by logging value of z in the loop. Example code: https://play.golang.org/p/9H7Uze4gip

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效