github.com/hedzr/evendeep@v0.4.8/internal/cl/parsecomplex115.go (about)

     1  //go:build go1.15
     2  // +build go1.15
     3  
     4  package cl
     5  
     6  import "strconv"
     7  
     8  // FormatComplex converts the complex number c to a string of the
     9  // form (a+bi) where a and b are the real and imaginary parts,
    10  // formatted according to the format fmt and precision prec.
    11  //
    12  // The format fmt and precision prec have the same meaning as in FormatFloat.
    13  // It rounds the result assuming that the original was obtained from a complex
    14  // value of bitSize bits, which must be 64 for complex64 and 128 for complex128.
    15  func FormatComplex(c complex128, fmt byte, prec, bitSize int) string {
    16  	if bitSize != 64 && bitSize != 128 {
    17  		panic("invalid bitSize")
    18  	}
    19  	bitSize >>= 1 // complex64 uses float32 internally
    20  
    21  	// Check if imaginary part has a sign. If not, add one.
    22  	im := strconv.FormatFloat(imag(c), fmt, prec, bitSize)
    23  	if im[0] != '+' && im[0] != '-' {
    24  		im = "+" + im
    25  	}
    26  
    27  	return "(" + strconv.FormatFloat(real(c), fmt, prec, bitSize) + im + "i)"
    28  }
    29  
    30  // ParseComplex converts a string to complex number.
    31  // If the string is not valid complex format, return err not nil.
    32  //
    33  // Examples:
    34  //
    35  //    c1 := cmdr.ParseComplex("3-4i")
    36  //    c2 := cmdr.ParseComplex("3.13+4.79i")
    37  func ParseComplex(s string) (v complex128, err error) {
    38  	return strconv.ParseComplex(s, 128) //nolint:gomnd //no need
    39  }