github.com/jingcheng-WU/gonum@v0.9.1-0.20210323123734-f1a2a11a8f7b/num/quat/abs.go (about)

     1  // Copyright ©2018 The Gonum Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Copyright 2017 The Go Authors. All rights reserved.
     6  // Use of this source code is governed by a BSD-style
     7  // license that can be found in the LICENSE file.
     8  
     9  package quat
    10  
    11  import "math"
    12  
    13  // Abs returns the absolute value (also called the modulus) of q.
    14  func Abs(q Number) float64 {
    15  	// Special cases.
    16  	switch {
    17  	case IsInf(q):
    18  		return math.Inf(1)
    19  	case IsNaN(q):
    20  		return math.NaN()
    21  	}
    22  
    23  	r, i, j, k := q.Real, q.Imag, q.Jmag, q.Kmag
    24  	if r < 0 {
    25  		r = -r
    26  	}
    27  	if i < 0 {
    28  		i = -i
    29  	}
    30  	if j < 0 {
    31  		j = -j
    32  	}
    33  	if k < 0 {
    34  		k = -k
    35  	}
    36  	if r < i {
    37  		r, i = i, r
    38  	}
    39  	if r < j {
    40  		r, j = j, r
    41  	}
    42  	if r < k {
    43  		r, k = k, r
    44  	}
    45  	if r == 0 {
    46  		return 0
    47  	}
    48  	i /= r
    49  	j /= r
    50  	k /= r
    51  	return r * math.Sqrt(1+i*i+j*j+k*k)
    52  }