[Go语言]我的第一个Go语言程序

本文通过使用Newton迭代法实现了一个简单的平方根计算函数。该函数首先选择一个初始值,并不断迭代更新直到达到预设的精度标准。我们还比较了自定义函数与标准库函数的计算结果。

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

Exercise: Loops and Functions

As a simple way to play with functions and loops, implement the square root function using Newton's method.

In this case, Newton's method is to approximate Sqrt(x) by picking a starting point z and then repeating:

To begin with, just repeat that calculation 10 times and see how close you get to the answer for various values (1, 2, 3, ...).

Next, change the loop condition to stop once the value has stopped changing (or only changes by a very small delta). See if that's more or fewer iterations. How close are you to the math.Sqrt?

package main

import (
	"fmt"
	"math"
)

var delta = 0.00001

func Sqrt(x float64) float64 {
	z := 1.0
	var z1 float64
	z1 = z - (z * z - x) / (2 * z)
	for math.Abs(z1 - z) > delta {
		z = z1
		z1 = z - (z * z - x) / (2 * z)
	}
	return z1;
}

func main() {
	fmt.Println(Sqrt(2))
	fmt.Println(math.Sqrt(2))
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值