Search code examples
rubymathpi

Calculate the value of PI using `pi = x * sin(180 / x)`


I have a problem using sin. I did:

include Math

puts sin(5) # => -0.9589242746631385

But when I type sin(5) into my calculator, it outputs 0.087155742. Likewise, I tried to calculate the value of PI using the equation pi = x * sin(180 / x) and got a problem although I got the value of PI with it on my calculator.

include Math

puts "Enter the value of x"
x = gets.to_f
num = 180 / x

pie = x * sin(num)
puts pie

Thanks if anyone can help.


Solution

  • Your equation is for a calculation of the sin of an angle in degrees.

    Most, maybe all, computer language sin() functions expect the angle to be in radians.

    Unfortunately, you need to have a value for pi to convert from one to another, so unless you can find a sin-in-degrees implementation you’re somewhat stuck.

    This is because your formula comes from the 2×π/360 or π/180 conversion between radians and degrees.