feat(utils): 新增快速平方根算法实现,包含卡马克算法及性能测试

This commit is contained in:
1
2025-07-30 02:27:58 +00:00
parent 1813155f8e
commit 3bbc786520
2 changed files with 154 additions and 0 deletions

91
common/utils/sqrt_test.go Normal file
View File

@@ -0,0 +1,91 @@
package utils
import (
"fmt"
"math"
"testing"
)
func Test_fastSqrt(t *testing.T) {
// 测试用例
testCases := []float64{2, 4, 10, 16, 25, 100, 1000, 0.5, 0.01, 1e-20}
fmt.Println("测试卡马克快速平方根算法与标准库的对比:")
fmt.Println("数值\t快速算法结果\t标准库结果\t绝对误差")
fmt.Println("--------------------------------------------------------------")
for _, x := range testCases {
fastResult := fastSqrt(x)
stdResult := math.Sqrt(x)
error := math.Abs(fastResult - stdResult)
fmt.Printf("%.10g\t%.10g\t\t%.10g\t\t%.2e\n",
x, fastResult, stdResult, error)
}
// 测试整数版本
fmt.Println("\n测试整数快速平方根算法")
fmt.Println("数值\t快速算法结果\t标准库转换结果")
fmt.Println("--------------------------------------")
for _, x := range []int{2, 4, 10, 16, 25, 100, 1000} {
fastResult := fastSqrtInt(x)
stdResult := int(math.Sqrt(float64(x)))
fmt.Printf("%d\t%d\t\t%d\n", x, fastResult, stdResult)
}
}
func BenchmarkMathSqrt(b *testing.B) {
testValues := []float64{2, 4, 10, 16, 25, 100, 1000, 0.5, 0.01, 1e-20}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for _, x := range testValues {
_ = math.Sqrt(x)
}
}
}
func BenchmarkFastSqrt(b *testing.B) {
testValues := []float64{2, 4, 10, 16, 25, 100, 1000, 0.5, 0.01, 1e-20}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for _, x := range testValues {
_ = fastSqrt(x)
}
}
}
func BenchmarkFastSqrtCarmack(b *testing.B) {
testValues := []float64{2, 4, 10, 16, 25, 100, 1000, 0.5, 0.01, 1e-20}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for _, x := range testValues {
_ = fastSqrtCarmack(x)
}
}
}
func BenchmarkMathSqrtInt(b *testing.B) {
testValues := []int{2, 4, 10, 16, 25, 100, 1000, 10000, 100000}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for _, x := range testValues {
_ = int(math.Sqrt(float64(x)))
}
}
}
func BenchmarkFastSqrtInt(b *testing.B) {
testValues := []int{2, 4, 10, 16, 25, 100, 1000, 10000, 100000}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for _, x := range testValues {
_ = fastSqrtInt(x)
}
}
}