登录
首页 >  Golang >  Go问答

算法 pi 在前几次迭代后开始归零

来源:stackoverflow

时间:2024-02-23 08:12:22 322浏览 收藏

偷偷努力,悄无声息地变强,然后惊艳所有人!哈哈,小伙伴们又来学习啦~今天我将给大家介绍《算法 pi 在前几次迭代后开始归零》,这篇文章主要会讲到等等知识点,不知道大家对其都有多少了解,下面我们就一起来看一吧!当然,非常希望大家能多多评论,给出合理的建议,我们一起学习,一起进步!

问题内容

我编写了一个算法来求 pi,方法是在直径为 1 的圆内内切一个正方形,使正方形的对角平分线长度为 1。这给了我 4 个边长为 0.5 的直角三角形,我可以使用它们余弦定律求正方形的周长。通过将每个角度减半并将每个三角形的边长保持为 0.5,我可以无限增加内部正方形的边数,使其接近其周围的圆的形状,该圆的周长为 1(pi),因为直径为 1 .

问题是,当我运行我的代码时,它开始接近 pi 直到它发送“4”,然后每个输出都变成 0,我做错了什么?

package main

import (
    "fmt"
    "math"
)

func findpi(angle, numsides float64) float64 {

    /*here i use cosine law to find the length of the c side of each inner triangle
      and multiply by the number of these inner triangles to find the perimeter*/

        return math.Sqrt(0.5-0.5*(math.Cos(angle*math.Pi/180))) * numsides
}

func main() {

    /*and here i halve the inner angle of the 4 triangles in the square repeatedly 
      as well as double the # of sides to approach a circle with perimeter pi*/

    for angle, numsides := 90.0, 4.0; angle > 0.000000001; angle, numsides = angle/2, numsides*2 {

        fmt.Println(findpi(angle, numsides))

    }

}

正确答案


这部分 math.Cos(angle2) 越来越接近 1,并且在某些时候您开始失去精度。 Float64 不是正确的类型。您可能需要使用 math/big 但我找不到余弦的示例。

也许你可以定义泰勒级数的前 N ​​项

到这里,我们也就讲完了《算法 pi 在前几次迭代后开始归零》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>