pi 查找算法适用于前几次迭代,然后开始返回 0

发布于 2025-01-19 12:23:08 字数 895 浏览 3 评论 0原文

我已经写了一种算法来找到PI,通过将正方形刻在直径1的圆中,以使正方形的对角线分配器长1。找到广场的周长。通过将每个角度放置并保持每个三角形的侧面长度为0.5,我可以无限期地增加内部正方形的边数,以便它接近周围圆的形状,因为直径为一个,它具有周围1(pi) 。

问题是,当我运行代码时,它开始接近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))

    }

}

I've written an algorithm to find pi by inscribing a square within a circle of diameter 1 so that the diagonal bisector of the square is of length 1. This gives me 4 right angle triangles with side length 0.5 that I can use cosine law on to find the perimeter of the square. By halving each angle and keeping the side length of each triangle 0.5, I can indefinitely increase the number of sides of the inside square so that it approaches the shape of the circle around it, which has perimeter 1(pi) since the diameter is one.

The problem is that when I run my code it starts to approach pi until it sends a "4" and then every output becomes 0, what am I doing wrong?

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))

    }

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

如此安好 2025-01-26 12:23:08

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

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

This part math.Cos(angle2) is getting close to 1 and at some point you start to loose precision. Float64 is not the right type. You may need to use math/big however I can’t find an example with cosine.

Perhaps you can define the first N terms of Taylor’s series

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文