Skip to content

Commit 7c29f6e

Browse files
committed
Use common prec validation also in BigDecimal#sqrt
1 parent d055b51 commit 7c29f6e

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
@@ -21,9 +21,13 @@ def self.coerce_to_bigdecimal(x, prec, method_name) # :nodoc:
2121
raise ArgumentError, "#{x.inspect} can't be coerced into BigDecimal"
2222
end
2323

24-
def self.validate_prec(prec, method_name) # :nodoc:
24+
def self.validate_prec(prec, method_name, accept_zero: false) # :nodoc:
2525
raise ArgumentError, 'precision must be an Integer' unless Integer === prec
26-
raise ArgumentError, "Zero or negative precision for #{method_name}" if prec <= 0
26+
if accept_zero
27+
raise ArgumentError, "Negative precision for #{method_name}" if prec < 0
28+
else
29+
raise ArgumentError, "Zero or negative precision for #{method_name}" if prec <= 0
30+
end
2731
end
2832

2933
def self.infinity_computation_result # :nodoc:
@@ -178,12 +182,12 @@ def power(y, prec = nil)
178182
# Result has at least prec significant digits.
179183
#
180184
def sqrt(prec)
185+
Internal.validate_prec(prec, :sqrt, accept_zero: true)
181186
if infinite? == 1
182187
exception_mode = BigDecimal.mode(BigDecimal::EXCEPTION_ALL)
183188
raise FloatDomainError, "Computation results in 'Infinity'" if exception_mode.anybits?(BigDecimal::EXCEPTION_INFINITY)
184189
return INFINITY
185190
end
186-
raise ArgumentError, 'negative precision' if prec < 0
187191
raise FloatDomainError, 'sqrt of negative value' if self < 0
188192
raise FloatDomainError, "sqrt of 'NaN'(Not a Number)" if nan?
189193
return self if zero?

0 commit comments

Comments
 (0)