A Tour of Go : Advanced Exercise: Complex cube roots

本文通过Go内置的复数类型complex64和complex128来演示复数运算,并实现了一个求立方根的算法。同时,展示了math/cmplx包中的Pow函数使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

A Tour of Go系列。如有问题欢迎指出~


这个也没什么好说的,就是试一下内建的复数运算。

Let's explore Go's built-in support for complex numbers via thecomplex64 and complex128 types. For cube roots, Newton's method amounts to repeating:

Newton's method

Find the cube root of 2, just to make sure the algorithm works. There is aPow function in the math/cmplx package.

代码:

 1 package main
 2 
 3 import (
 4     "fmt"
 5     "math/cmplx"
 6 )
 7 
 8 func Cbrt(x complex128) complex128 {
 9     z:=complex128(1)
10     for i:=0;i<10;i++{
11         z=z-(z*z*z-x)/(3*z*z)
12     }
13     return z
14 }
15 
16 func main() {
17     fmt.Println(Cbrt(2))
18     fmt.Println(cmplx.Pow(2,1.0/3))
19 }

将输出:

(1.2599210498948732+0i)
(1.259921049894873+0i)

注意一下cmplx.Pow的用法。

 

转载于:https://www.cnblogs.com/so-what/archive/2012/10/11/2720574.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值