簡體   English   中英

如何在 Go 中取立方根?

[英]How to take a cube root in Go?

我正在使用牛頓法在 Google Go 中編寫立方根函數。 我想使用 math/ cmplx.Pow()檢查結果,但對於我來說,我無法弄清楚如何。 我該怎么做呢?

您是否嘗試過myCubicRootOfx = Pow(x, 1.0/3)

編輯:感謝Jason McCreary評論:
我們不能使用1/3作為Pow的第二個參數,因為這是一個整數除法,因此不會產生預期的 1/3 值。 通過使用1.0/31/3.0等,我們有效地生成了一個具有 0.333333... 值的浮點數。

作為圍棋練習 47的一部分,我使用牛頓法編寫了立方根函數。 也許下面的兩個函數( Cbrt1Cbrt )會有所幫助。

package main

import (
    "fmt"
    "math/cmplx"
)

// Newton's method cube root function that hopes for
//   convergence within 20 iterations
func Cbrt1(x complex128) complex128 {
    var z complex128 = x
    for i:= 0; i < 20; i++ {
        z = z - ((z*z*z - x) / (3.0*z*z))
    }
    return z
}

// Newton's method cube root function that runs until stable
func Cbrt(x complex128) complex128 {
    var z, z0 complex128 = x, x
    for {
        z = z - ((z*z*z - x) / (3.0*z*z))
        if cmplx.Abs(z - z0) < 1e-10 {
            break
        }
        z0 = z
    }
    return z
}

func main() {
    fmt.Println(Cbrt(2.0) , "should match" , cmplx.Pow(2, 1.0/3.0))
}

當您使用牛頓法時,我想您是從一個正實數開始的。

所以你不需要復雜的數字。

你可以簡單地做

package main

import (
    "fmt"
    "math"
)

func main() {
    x := 100.0
    root := math.Pow(x, 1.0/3.0)
    fmt.Println(root)
}

例如,

package main

import (
    "fmt"
    "math/cmplx"
)

func main() {
    var x complex128
    x = -8
    y := cmplx.Pow(x, 1.0/3.0)
    fmt.Println(y)
    x = -27i
    y = cmplx.Pow(x, 1.0/3.0)
    fmt.Println(y)
    x = -8 - 27i
    y = cmplx.Pow(x, 1.0/3.0)
    fmt.Println(y)
    x = complex(-8, -27)
    y = cmplx.Pow(x, 1.0/3.0)
    fmt.Println(y)
}

輸出:

(1+1.732050807568877i)
(2.5980762113533156-1.4999999999999996i)
(2.4767967587776756-1.7667767800295509i)
(2.4767967587776756-1.7667767800295509i)

Go 編程語言規范

包 cmplx

看起來 go 比其他一些答案最近發生了變化,所以我想我會更新 - 他們將 cuberoot 直接構建到math中作為Cbrt 它接受並返回一個float64 快速參考在godoc math | grep Cbrt godoc math | grep Cbrt (如果你安裝了godoc ,我強烈推薦)

import "math"

func main() {
    var x float64 = math.Cbrt(8)
    fmt.Println(x) // prints 2
}

嘗試這樣的事情

package main

import(
        "fmt"
        "math/cmplx"
    )


func Cbrt(x complex128) complex128 {
    z := complex128(1)


    for i:=0;i<100;i++ {  // OR JUST for{ since you will outrun complex128 in worth case
      last_z := z

      z = z - ((z*z*z - x)/(3 *z*z))    
      if last_z == z{
        return z
      }
    }
    return z
}

func main() {
    fmt.Println("good enough", Cbrt(9))
    fmt.Println("builtin", cmplx.Pow(9, 1.0/3.0))
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM