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 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥30 用arduino开发esp32控制ps2手柄一直报错
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿