The Go Programming Language
› http://golang.org/
› Go Playground
Go Projects
› Revel Web Framework
sxshi110

go 中的 hypot 实现疑问。

  •  
  •   sxshi110 · Dec 11, 2019 · 3990 views
    This topic created in 2521 days ago, the information mentioned may be changed or developed.

    go 中的 hypot 实现源码:

    func hypot(p, q float64) float64 {
    	// special cases
    	switch {
    	case IsInf(p, 0) || IsInf(q, 0):
    		return Inf(1)
    	case IsNaN(p) || IsNaN(q):
    		return NaN()
    	}
    	p, q = Abs(p), Abs(q)
    	if p < q {
    		p, q = q, p
    	}
    	if p == 0 {
    		return 0
    	}
    	q = q / p
    	return p * Sqrt(1+q*q)
    }
    

    为什么不直接这样实现:

    func hypot(p, q float64) float64 {
    	switch {
    	case IsInf(p, 0) || IsInf(q, 0):
    		return Inf(1)
    	case IsNaN(p) || IsNaN(q):
    		return NaN()
    	}
    	return Sqrt(p*p+q*q)
    }
    

    请教其中有什么差别

    4 replies  •  2019-12-12 12:28:06 +08:00
    wangsyi13
    wangsyi13
    Dec 11, 2019
    1
    不知道,等大神解答。。
    0ZXYDDu796nVCFxq
    0ZXYDDu796nVCFxq
    Dec 11, 2019 via Android❤️1
    2
    防止溢出
    StarUDream
    StarUDream
    Dec 11, 2019
    3
    二楼正解,p*p+q*q 这个值可能溢出
    sxshi110
    sxshi110
    OP
    Dec 12, 2019
    4
    @gstqc
    感谢,想想确实是这个思路。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   3652 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 05:19 · PVG 13:19 · LAX 21:19 · JFK 00:19
    ♥ Do have faith in what you're doing.