Skip to content

Commit db8554d

Browse files
committed
Use common prec validation also in BigDecimal#sqrt
1 parent cac4ecc commit db8554d

File tree

1 file changed

+7
-3
lines changed

1 file changed

+7
-3
lines changed

lib/bigdecimal.rb

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -133,12 +133,12 @@ def power(y, prec = nil)
133133
# Result has at least prec significant digits.
134134
#
135135
def sqrt(prec)
136+
BigMath._validate_prec(prec, :sqrt, accept_zero: true)
136137
if infinite? == 1
137138
exception_mode = BigDecimal.mode(BigDecimal::EXCEPTION_ALL)
138139
raise FloatDomainError, "Computation results in 'Infinity'" if exception_mode.anybits?(BigDecimal::EXCEPTION_INFINITY)
139140
return INFINITY
140141
end
141-
raise ArgumentError, 'negative precision' if prec < 0
142142
raise FloatDomainError, 'sqrt of negative value' if self < 0
143143
raise FloatDomainError, "sqrt of 'NaN'(Not a Number)" if nan?
144144
return self if zero?
@@ -177,9 +177,13 @@ def self._coerce_to_bigdecimal(x, method_name, complex_domain_error = false)
177177
raise ArgumentError, "#{x.inspect} can't be coerced into BigDecimal"
178178
end
179179

180-
def self._validate_prec(prec, method_name)
180+
def self._validate_prec(prec, method_name, accept_zero: false)
181181
raise ArgumentError, 'precision must be an Integer' unless Integer === prec
182-
raise ArgumentError, "Zero or negative precision for #{method_name}" if prec <= 0
182+
if accept_zero
183+
raise ArgumentError, "Negative precision for #{method_name}" if prec < 0
184+
else
185+
raise ArgumentError, "Zero or negative precision for #{method_name}" if prec <= 0
186+
end
183187
end
184188

185189
# call-seq:

0 commit comments

Comments
 (0)