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

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

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100