Skip to content

Commit 92a9d7e

Browse files
authored
Make bigdecimal.rb work in JRuby (#420)
Use BigDecimal(float, 0) instead of BigDecimal(float). Add a ruby-implemented polyfill of BigDecimal#_decimal_shift. This is needed to let math.rb depend on bigdecimal.rb utility methods.
1 parent cebd1a5 commit 92a9d7e

2 files changed

Lines changed: 17 additions & 5 deletions

File tree

lib/bigdecimal.rb

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
if RUBY_ENGINE == 'jruby'
22
JRuby::Util.load_ext("org.jruby.ext.bigdecimal.BigDecimalLibrary")
3-
return
3+
4+
class BigDecimal
5+
def _decimal_shift(i) # :nodoc:
6+
to_java.move_point_right(i).to_d
7+
end
8+
end
49
else
510
require 'bigdecimal.so'
611
end
@@ -15,7 +20,7 @@ def self.coerce_to_bigdecimal(x, prec, method_name) # :nodoc:
1520
when BigDecimal
1621
return x
1722
when Integer, Float
18-
return BigDecimal(x)
23+
return BigDecimal(x, 0)
1924
when Rational
2025
return BigDecimal(x, [prec, 2 * BigDecimal.double_fig].max)
2126
end
@@ -199,7 +204,7 @@ def sqrt(prec)
199204

200205
ex = exponent / 2
201206
x = _decimal_shift(-2 * ex)
202-
y = BigDecimal(Math.sqrt(x.to_f))
207+
y = BigDecimal(Math.sqrt(x.to_f), 0)
203208
precs = [prec + BigDecimal.double_fig]
204209
precs << 2 + precs.last / 2 while precs.last > BigDecimal.double_fig
205210
precs.reverse_each do |p|

test/bigdecimal/test_jruby.rb

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,13 @@ class TestJRuby < Test::Unit::TestCase
1010

1111
N = 20
1212

13+
def test_decimal_shift_polyfill
14+
assert_equal(BigDecimal('123.45e2'), BigDecimal('123.45')._decimal_shift(2))
15+
assert_equal(BigDecimal('123.45e-2'), BigDecimal('123.45')._decimal_shift(-2))
16+
assert_equal(BigDecimal('123.45e10000'), BigDecimal('123.45')._decimal_shift(10000))
17+
assert_equal(BigDecimal('123.45e-10000'), BigDecimal('123.45')._decimal_shift(-10000))
18+
end
19+
1320
def test_sqrt
1421
sqrt2 = BigDecimal(2).sqrt(N)
1522
assert_in_delta(Math.sqrt(2), sqrt2)
@@ -35,10 +42,10 @@ def test_power
3542
expected = 2 ** 2.5
3643
assert_in_delta(expected, x ** BigDecimal('2.5'))
3744
assert_in_delta(expected, x.sqrt(N) ** 5)
38-
# assert_in_delta(expected, x ** 2.5)
45+
assert_in_delta(expected, x ** 2.5)
3946
assert_in_delta(expected, x ** 2.5r)
4047
assert_in_delta(expected, x.power(BigDecimal('2.5'), N))
41-
# assert_in_delta(expected, x.power(2.5, N))
48+
assert_in_delta(expected, x.power(2.5, N))
4249
assert_in_delta(expected, x.sqrt(N).power(5, N))
4350
assert_in_delta(expected, x.power(2.5r, N))
4451
end

0 commit comments

Comments
 (0)