Math
suggest changeThe built-in Math module in Ruby contains mathematical functions and constants for real numbers (using system C library floating-point math). Module methods can be called directly on Math, or the module can be included into classes or scripts for convenient access.
1. Mathematical Constants
Math defines fundamental mathematical constants as module constants:
puts Math::PI # => 3.141592653589793
puts Math::E # => 2.718281828459045
2. Square Roots, Cube Roots, and Hypot
Roots
# Square root
puts Math.sqrt(25) # => 5.0
puts Math.sqrt(2) # => 1.4142135623730951
# Cube root
puts Math.cbrt(27) # => 3.0
puts Math.cbrt(-8) # => -2.0
Euclidean Distance (hypot)
Math.hypot(x, y) calculates the hypotenuse $\sqrt{x^2 + y^2}$ without intermediate overflow or underflow:
dx = 3.0
dy = 4.0
distance = Math.hypot(dx, dy)
puts distance # => 5.0
3. Logarithms and Exponents
Math provides natural logarithms, base-2, base-10, and arbitrary base logarithms:
# Natural logarithm (base e)
puts Math.log(Math::E) # => 1.0
# Arbitrary base logarithm: Math.log(x, base)
puts Math.log(8, 2) # => 3.0
puts Math.log(100, 10) # => 2.0
# Base-2 and Base-10 shortcuts
puts Math.log2(64) # => 6.0
puts Math.log10(1000) # => 3.0
# Exponential e^x
puts Math.exp(1) # => 2.718281828459045
puts Math.exp(2) # => 7.38905609893065
4. Trigonometry
Trigonometric functions expect angles in radians:
# Degrees to radians helper: rad = deg * (PI / 180)
degrees = 90
radians = degrees * (Math::PI / 180.0)
# Sine, Cosine, and Tangent
puts Math.sin(radians) # => 1.0
puts Math.cos(radians) # => 6.123233995736766e-17 (approx 0.0)
puts Math.tan(0) # => 0.0
# Inverse trigonometry (arc sine, arc cosine, arc tangent)
puts Math.asin(1.0) * (180.0 / Math::PI) # => 90.0 degrees
# Math.atan2(y, x) computes atan(y/x) using signs to determine the quadrant
angle = Math.atan2(1.0, -1.0)
puts angle * (180.0 / Math::PI) # => 135.0 degrees
5. Domain Errors and Negative Values
Attempting a real math operation outside a function's domain (such as square root or logarithm of a negative number) raises Math::DomainError:
begin
Math.sqrt(-4)
rescue Math::DomainError => e
puts "Domain error caught: #{e.message}"
end
Note: If you need complex number support (e.g. $\sqrt{-4} = 2i$), use
Complex(-4) ** 0.5(=>(0.0+2.0i)) instead; the oldcmathlibrary was removed in Ruby 2.7. Note thatMath.log(0)does not raise; it returns-Infinity.
6. Including the Math Module
You can include Math directly in a class or the top-level script to call math functions without prefixing Math.:
class PolarPoint
include Math
attr_reader :radius, :theta
def initialize(radius, theta_degrees)
@radius = radius
@theta = theta_degrees * (PI / 180.0)
end
def x
radius * cos(theta)
end
def y
radius * sin(theta)
end
end
point = PolarPoint.new(10, 45)
puts "x: #{point.x.round(2)}, y: #{point.y.round(2)}"
# => x: 7.07, y: 7.07