take the cosine of a number in ruby

To take the cosine of a number in Ruby, we can use the cos method of the Math module. Here's an example:

main.rb
x = 0.5
cos_x = Math.cos(x)
puts cos_x
39 chars
4 lines

In this example, we first assign a value of 0.5 to the variable x. Then, we use the Math.cos method to find the cosine of x, and assign the result to the variable cos_x. Finally, we use the puts method to output the value of cos_x to the console.

Note that the argument to Math.cos should be in radians. If you have an angle in degrees, you can convert it to radians using the deg2rad method:

main.rb
degrees = 45
radians = Math::PI / 180 * degrees
cos_x = Math.cos(radians)
puts cos_x
85 chars
5 lines

In this example, we first set the value of degrees to 45. We then convert this to radians using the formula radians = Math::PI / 180 * degrees, which takes advantage of the fact that there are 2 * pi radians in a circle and 360 degrees in a circle. Finally, we use the same procedure as before to find the cosine of radians.

gistlibby LogSnag