Introduction To Ruby
The Math Module

The Math module is packed full of useful mathematical methods. It also has a few useful constants defined as floating point numbers,

# Math Module Constants

a = Math::PI
b = Math::E

puts a
puts b



Like most languages, Ruby uses radians as a unit for angles.

acos(x)Computes the arc cosine of xNumberFloat
acosh(x)Computes the inverse hyperbolic cosine of xNumberFloat
asin(x)Computes the arc sine of xNumberFloat
asinh(x)Computes the inverse hyperbolic sine of xNumberFloat
atan(x)Computes the arc tangent of xNumberFloat
atan2(y,x)Computes the arc tangent given y and xNumbersFloat
atanh(x)Computes the inverse hyperbolic tangent of xNumberFloat
cbrt(x)Computes the cube root of xNumberFloat
cos(x)Computes the cosine of xNumberFloat
cosh(x)Computes the hyperbolic cosine of xNumberFloat
erf(x)Computes the error function of xNumberFloat
erfc(x)Computes the complementary error function of xNumberFloat
exp(x)Computes e to the power of xNumberFloat
hypot(x,y)Computes the hypotenuse of a right angled triangle with sides x and yNumberFloat
log(x)Computes the natural logarithm of xNumberFloat
log(x,y)Computes the base y logarithm of xNumbersFloat
log10(x)Computes the base 10 logarithm of xNumberFloat
sinx(x)Computes the sine of xNumberFloat
sinh(x)Computes the hyperbolic sine of xNumberFloat
sqrt(x)Computes the square root of xNumberFloat
tan(x)Computes the tangent of xNumberFloat
tanh(x)Computes the hyperbolic tangent of xNumberFloat


Here is a short example using a Math method.

# Math Module

print "Enter side a: "
a = gets.chomp.to_i
print "Enter side b: "
b = gets.chomp.to_i

c = Math.hypot(a,b)
puts "The hypotenuse is #{c}"



The use you will make of the Math module is going to depend on the level of Maths that you work at. Whilst lots of complex mathematical processes can be programmed without troubling the Math module, its functions are useful for lots of processes. Think through the things you have been learning in Maths and try to develop some programs to assist with the calculations.

If you are struggling for ideas, a program that solves any triangle, given enough information from the user, is a decent challenge.