Math::DomainError
RubyERRORNotableMath
Math function input outside its domain
Quick Answer
Clamp or validate numeric inputs before calling Math module functions.
What this means
Raised by functions in the Math module when a numeric argument falls outside the mathematical domain of the function. It is a subclass of ArgumentError and distinct from FloatDomainError.
Why it happens
- 1Math.asin or Math.acos called with a value outside [-1, 1]
- 2Math.log called with a non-positive value
- 3Math.sqrt called with a negative Float
Fix
Clamp input for asin/acos
Clamp input for asin/acos
def safe_acos(x) Math.acos(x.clamp(-1.0, 1.0)) end
Why this works
Clamping ensures floating-point rounding errors near -1 or 1 do not push the value out of domain.
Code examples
acos out of domainruby
Math.acos(1.0001) # Math::DomainError: Numerical argument is out of domain - "acos"
Rescue Math::DomainErrorruby
begin angle = Math.acos(value) rescue Math::DomainError angle = 0.0 end
Checking ancestryruby
Math::DomainError < ArgumentError # => true Math::DomainError < StandardError # => true
Same error in other languages
Sources
Official documentation ↗
Ruby Core Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev