在 Go 語言中查詢複數的平方根
在數學中,一個數的平方根是指一個值,當它自身相乘時,會得到原始數字。在 Go 語言中,math/cmplx 包提供了內建函式來查詢複數的平方根。在本文中,我們將討論如何使用示例在 Go 語言中查詢複數的平方根。
示例 1:查詢複數的平方根
讓我們考慮一個使用 Go 語言查詢複數平方根的示例。假設我們要查詢 z = 3 + 4i 的平方根。以下是實現此目的的程式碼片段:
package main
import (
"fmt"
"math/cmplx"
)
func main() {
// Creating a complex number
z := complex(3, 4)
// Finding the square root of the complex number
sqrtZ := cmplx.Sqrt(z)
// Displaying the result
fmt.Println("Square Root of", z, "is", sqrtZ)
}
輸出
Square Root of (3+4i) is (2+1i)
在此示例中,我們首先建立一個複數 z,然後使用 cmplx.Sqrt() 函式查詢其平方根並將結果儲存在 sqrtZ 中。該程式的輸出將是:
示例 2:查詢純虛數的平方根
讓我們考慮一個使用 Go 語言查詢純虛數平方根的示例。假設我們要查詢 y = 2i 的平方根。以下是實現此目的的程式碼片段:
package main
import (
"fmt"
"math/cmplx"
)
func main() {
// Creating a purely imaginary number
y := 2i
// Finding the square root of the purely imaginary number
sqrtY := cmplx.Sqrt(y)
// Displaying the result
fmt.Println("Square Root of", y, "is", sqrtY)
}
輸出
Square Root of (0+2i) is (1+1i)
在此示例中,我們首先建立了一個純虛數 y,然後使用 cmplx.Sqrt() 函式查詢其平方根並將結果儲存在 sqrtY 中。
示例 3:查詢負實數的平方根
讓我們考慮一個使用 Go 語言查詢負實數平方根的示例。假設我們要查詢 -4 的平方根。以下是實現此目的的程式碼片段:
package main
import (
"fmt"
"math/cmplx"
)
func main() {
// Creating a negative real number
z := -4.0
// Finding the square root of the negative real number
sqrtZ := cmplx.Sqrt(complex(z, 0))
// Displaying the result
fmt.Println("Square Root of", z, "is", sqrtZ)
}
輸出
Square Root of -4 is (0+2i)
在此示例中,我們首先建立了一個負實數 z,然後使用 cmplx.Sqrt() 函式查詢其平方根並將結果儲存在 sqrtZ 中。由於負實數的平方根是一個複數,因此我們需要將 z 作為具有 0 虛部的複數傳遞。
示例 4:查詢複數的多個平方根
在 Go 語言中,我們可以找到複數的多個平方根。對於給定的複數 z = x + yi,我們可以使用以下公式找到平方根:
sqrt(z) = +/- sqrt(r) * [cos((theta + 2k*pi)/2) + i*sin((theta + 2k*pi)/2)], k = 0, 1
其中 r = |z| 是複數 z 的模,theta = arg(z) 是複數 z 的輻角。
讓我們考慮一個示例,其中我們要查詢複數 z = 3 + 4i 的兩個平方根。以下是實現此目的的程式碼片段:
package main
import (
"fmt"
"math/cmplx"
)
func main() {
// Creating a complex number
z := complex(3, 4)
// Finding the square roots of the complex number
sqrt1 := cmplx.Sqrt(z)
sqrt2 := -cmplx.Sqrt(z)
// Displaying the result
fmt.Printf("Square Roots of %v are:\n%v\n%v", z, sqrt1, sqrt2)
}
輸出
Square Roots of (3+4i) are: (2+1i) (-2-1i)
結論
藉助 cmplx.Sqrt() 函式,在 Go 語言中查詢複數的平方根非常簡單。透過使用此函式,我們可以輕鬆計算任何複數的平方根,無論是純實數還是純虛數,或者兩者的組合。此外,我們可以使用 cmplx.Pow() 函式查詢複數的任何 n 次方根。需要注意的是,在求複數的根時,可能有多個解,因此我們需要仔細選擇適合我們用例的解。透過本文提供的知識和示例,您應該能夠使用 Go 語言在您的專案中有效地計算複數的平方根。
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP