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
gets
Methods
Like most languages, Ruby uses radians as a unit for angles.
Method | Description | Accepts | Returns |
---|---|---|---|
acos(x) | Computes the arc cosine of x | Number | Float |
acosh(x) | Computes the inverse hyperbolic cosine of x | Number | Float |
asin(x) | Computes the arc sine of x | Number | Float |
asinh(x) | Computes the inverse hyperbolic sine of x | Number | Float |
atan(x) | Computes the arc tangent of x | Number | Float |
atan2(y,x) | Computes the arc tangent given y and x | Numbers | Float |
atanh(x) | Computes the inverse hyperbolic tangent of x | Number | Float |
cbrt(x) | Computes the cube root of x | Number | Float |
cos(x) | Computes the cosine of x | Number | Float |
cosh(x) | Computes the hyperbolic cosine of x | Number | Float |
erf(x) | Computes the error function of x | Number | Float |
erfc(x) | Computes the complementary error function of x | Number | Float |
exp(x) | Computes e to the power of x | Number | Float |
hypot(x,y) | Computes the hypotenuse of a right angled triangle with sides x and y | Number | Float |
log(x) | Computes the natural logarithm of x | Number | Float |
log(x,y) | Computes the base y logarithm of x | Numbers | Float |
log10(x) | Computes the base 10 logarithm of x | Number | Float |
sinx(x) | Computes the sine of x | Number | Float |
sinh(x) | Computes the hyperbolic sine of x | Number | Float |
sqrt(x) | Computes the square root of x | Number | Float |
tan(x) | Computes the tangent of x | Number | Float |
tanh(x) | Computes the hyperbolic tangent of x | Number | Float |
Example
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}"
gets
Challenges
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.