pi 查找算法适用于前几次迭代,然后开始返回 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这部分
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