doushichun9409 2019-07-27 19:58
浏览 96

试图计算圆周率,我在做什么错? math.Cos可能有问题吗?

I'm drawing a square inside a circle of diameter 1, the diagonal of the square is the diameter of the circle. I then split this square into 4 right angled triangles, using cosine law and knowing that the lengths of a and b on the triangle are 0.5, I create 4 triangles whose hypotenuses add together to form the perimeter of the square. Giving us the equation perimeter = number of sides * (a^2 + b^2 -2abcos(360 / number of sides)) By increasing the number of sides on this shape the perimeter gets closer and closer to the perimeter of the circle (3.14).

I've done this in python before, and it worked, but there was a problem with using cosine law on degrees instead of rad in python that messed it up.

package main

import "fmt"
import "math"

func main() {

    for n := float64(4) ; n == n; n *= 2 {
        fmt.Println(n)
        c := math.Pow(0.5 - (0.5 * math.Cos(360 / n)), 0.5)
        fmt.Println(c * n)
    }

}

The answer should start at about 3, and go up approaching 3.14, but instead the answer goes up to 180 instead. I've checked my math over and over again, but I think it's a problem with the language not what I am doing.

  • 写回答

1条回答 默认 最新

  • duanbairan4235 2019-07-30 02:56
    关注

    Don't use the standard function Cos - as many people have said, to use that you need to already know the value of pi because it takes its argument in radians.

    Most computer languages' trigonometric functions use radians as their arguments. This is because there are nice, simple formulas for approximating trig. functions if you use radians.

    In any case though, here you don't need it! You're doubling the value of n each time, so you can use the well-known half-angle formula for cosine:

    package main
    
    import "fmt"
    import "math"
    
    func main() {
        cosVal := float64(-1) // Start at cosine of 180 degrees
        for n := 4 ; n < 5000; n *= 2 {
            fmt.Println(n)
            cosVal = math.Sqrt(0.5 * (cosVal + 1.0))
            c := math.Pow(0.5 - 0.5*cosVal, 0.5)
            fmt.Println(c * float64(n))
        }
    
    }
    

    This converges as desired.


    Incidentally, note that initially you wanted something that converged to half a circle in radians (that is, to pi), but instead got something that converged to half a circle in degrees (that is, to 180). This is precisely because you handed degrees to Cos when you should have handed it radians.

    评论

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题