LEFT | RIGHT |
(no file at all) | |
| 1 // Copyright 2012 The Go 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 |
1 package main | 5 package main |
2 | 6 |
3 import ( | 7 import ( |
4 "fmt" | 8 "fmt" |
5 "math/cmplx" | 9 "math/cmplx" |
6 ) | 10 ) |
7 | 11 |
8 const delta = 1e-10 | 12 const delta = 1e-10 |
9 | 13 |
10 func Cbrt(x complex128) complex128 { | 14 func Cbrt(x complex128) complex128 { |
11 z := x | 15 z := x |
12 for { | 16 for { |
13 n := z - (z*z*z-x)/(3*z*z) | 17 n := z - (z*z*z-x)/(3*z*z) |
14 if cmplx.Abs(n-z) < delta { | 18 if cmplx.Abs(n-z) < delta { |
15 break | 19 break |
16 } | 20 } |
17 z = n | 21 z = n |
18 } | 22 } |
19 return z | 23 return z |
20 } | 24 } |
21 | 25 |
22 func main() { | 26 func main() { |
23 const x = 2 | 27 const x = 2 |
24 mine, theirs := Cbrt(x), cmplx.Pow(x, 1./3.) | 28 mine, theirs := Cbrt(x), cmplx.Pow(x, 1./3.) |
25 fmt.Println(mine, theirs, mine-theirs) | 29 fmt.Println(mine, theirs, mine-theirs) |
26 } | 30 } |
LEFT | RIGHT |