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