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

go 中的 hypot 实现疑问。

  •  
  •   sxshi110 · Dec 11, 2019 · 3613 views
    This topic created in 2350 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
        1
    wangsyi13  
       Dec 11, 2019
    不知道,等大神解答。。
    0ZXYDDu796nVCFxq
        2
    0ZXYDDu796nVCFxq  
       Dec 11, 2019 via Android   ❤️ 1
    防止溢出
    StarUDream
        3
    StarUDream  
       Dec 11, 2019
    二楼正解,p*p+q*q 这个值可能溢出
    sxshi110
        4
    sxshi110  
    OP
       Dec 12, 2019
    @gstqc
    感谢,想想确实是这个思路。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3000 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 12:53 · PVG 20:53 · LAX 05:53 · JFK 08:53
    ♥ Do have faith in what you're doing.