Skip to content

End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

class method

Math.sqrt

Math.sqrt(x) → Float

Returns the non-negative square root of x.

Domain: [0, INFINITY)

Codomain:[0, INFINITY)

Example
0.upto(10) {|x|
  p [x, Math.sqrt(x), Math.sqrt(x)**2]
}
#=> [0, 0.0, 0.0]
#   [1, 1.0, 1.0]
#   [2, 1.4142135623731, 2.0]
#   [3, 1.73205080756888, 3.0]
#   [4, 2.0, 4.0]
#   [5, 2.23606797749979, 5.0]
#   [6, 2.44948974278318, 6.0]
#   [7, 2.64575131106459, 7.0]
#   [8, 2.82842712474619, 8.0]
#   [9, 3.0, 9.0]
#   [10, 3.16227766016838, 10.0]

Note that the limited precision of floating point arithmetic might lead to surprising results:

Example
Math.sqrt(10**46).to_i  #=> 99999999999999991611392 (!)

See also BigDecimal#sqrt and Integer.sqrt.

See also .sinh .tan .sin .tanh also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.0