Section 5.23. More Advanced Trigonometry


5.22. Trigonometry in Degrees, Radians, and Grads

When it comes to measuring arc, the mathematical or "natural" unit is the radian, defined in such a way that an angle of one radian corresponds to an arclength equal to the radius of the circle. A little thought will show that there are 2π radians in a circle.

The degree of arc, which we use in everyday life is a holdover from ancient Babylonian base-60 units; this system divides the circle into 360 degrees. The less-familiar grad is a pseudometric unit defined in such a way that there are 100 grads in a right angle (or 400 in a circle).

Programming languages often default to the radian when calculating trigonometric functions, and Ruby is no exception. But we show here how to do these calculations in degrees or grads, in the event that any of our readers are engineers or ancient Babylonians.

Because the number of units in a circle is a simple constant, it follows that there are simple conversion factors between all these units. We define these here and simply use the constant names in subsequent code. As a matter of convenience, we'll stick them in the Math module:

module Math   RAD2DEG  = 360.0/(2.0*PI)  # Radians to degrees   RAD2GRAD = 400.0/(2.0*PI)  # Radians to grads end


Now we can define new trig functions if we want. Because we are converting to radians in each case, we will divide by the conversion factor we calculated previously. We could place these in the Math module if we wanted, though we don't show it here.

def sin_d(theta)   Math.sin (theta/Math::RAD2DEG) end def sin_g(theta)   Math.sin (theta/Math::RAD2GRAD) end


Of course, the corresponding cos and tan functions may be similarly defined.

The atan2 function is a little different. It takes two arguments (the opposite and adjacent legs of a right triangle) and returns an angle. Thus we convert the result, not the argument, handling it this way:

def atan2_d(y,x)   Math.atan2(y,x)/Math::RAD2DEG end def atan2_g(y,x)   Math.atan2(y,x)/Math::RAD2GRAD end





The Ruby Way(c) Solutions and Techniques in Ruby Programming
The Ruby Way, Second Edition: Solutions and Techniques in Ruby Programming (2nd Edition)
ISBN: 0672328844
EAN: 2147483647
Year: 2004
Pages: 269
Authors: Hal Fulton

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net