This is the version of a pure imaginary real number raised to the power of n (integer):
// ImagXpowN computes (x⋅i)ⁿ // // (x⋅i)¹ = x¹⋅i (x⋅i)² = -x² (x⋅i)³ = -x³ ⋅i (x⋅i)⁴ = x⁴ // (x⋅i)⁵ = x⁵⋅i (x⋅i)⁶ = -x⁶ (x⋅i)⁷ = -x⁷ ⋅i (x⋅i)⁸ = x⁸ // (x⋅i)⁹ = x⁹⋅i (x⋅i)¹⁰ = -x¹⁰ (x⋅i)¹¹ = -x¹¹⋅i (x⋅i)¹² = x¹² // func ImagXpowN(x float64, n int) complex128 { if n == 0 { return 1 } xn := math.Pow(x, float64(n)) switch n % 4 { case 1: return complex(0, xn) case 2: return complex(-xn, 0) case 3: return complex(0, -xn) } return complex(xn, 0) } These are the benchmark functions: func BenchmarkImagXpowN(b *testing.B) { x := 2.5 for i := 0; i < b.N; i++ { for n := 0; n < 200; n++ { ImagXpowN(x, n) } } } func BenchmarkImagXpowNcmplx(b *testing.B) { x := 2.5 for i := 0; i < b.N; i++ { for n := 0; n < 200; n++ { cmplx.Pow(complex(0, x), complex(float64(n), 0)) } } } With the following results: BenchmarkImagXpowN-32 200000 10299 ns/op BenchmarkImagXpowNcmplx-32 100000 18595 ns/op Now it's "just" 1.8x faster. Cheers D On Friday, August 4, 2017 at 10:43:41 AM UTC+10, Dorival Pedroso wrote: > > Hi, > > This is an interesting benchmark: > > Given this function: > // ImagPowN computes iⁿ = (√-1)ⁿ > // > // i¹ = i i² = -1 i³ = -i i⁴ = 1 > // i⁵ = i i⁶ = -1 i⁷ = -i i⁸ = 1 > // i⁹ = i i¹⁰ = -1 i¹¹ = -i i¹² = 1 > // > func ImagPowN(n int) complex128 { > if n == 0 { > return 1 > } > switch n % 4 { > case 1: > return 1i > case 2: > return -1 > case 3: > return -1i > } > return 1 > } > > And this benchmark test: > var ( > imagpownRes complex128 > ) > > func BenchmarkImagPowN(b *testing.B) { > var res complex128 > for i := 0; i < b.N; i++ { > for n := 0; n < 200; n++ { > res = ImagPowN(n) > } > } > imagpownRes = res > } > > func BenchmarkImagPowNcmplx(b *testing.B) { > var res complex128 > for i := 0; i < b.N; i++ { > for n := 0; n < 200; n++ { > res = cmplx.Pow(1i, complex(float64(n), 0)) > } > } > imagpownRes = res > } > > We get this output ( go test -run=XXX -bench=. ): > BenchmarkImagPowN-32 3000000 470 ns/op > BenchmarkImagPowNcmplx-32 200000 10050 ns/op > > A 20x speed up... > > Cheers. > Dorival > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.