From c995315153f7403636ec0d6119b7885668b32039 Mon Sep 17 00:00:00 2001 From: nobu Date: Wed, 6 Jun 2018 14:01:43 +0000 Subject: [PATCH] math.c: adjust cbrt * math.c (math_cbrt): refine the approximation result on boundary values by an iteration of Newton-Raphson method. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@63592 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- math.c | 9 ++++++++- test/ruby/test_math.rb | 1 + 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/math.c b/math.c index 0b15ba7056..509cd46ef2 100644 --- a/math.c +++ b/math.c @@ -689,7 +689,14 @@ rb_math_sqrt(VALUE x) static VALUE math_cbrt(VALUE unused_obj, VALUE x) { - return DBL2NUM(cbrt(Get_Double(x))); + double f = Get_Double(x); + double r = cbrt(f); +#if defined __GLIBC__ + if (isfinite(r)) { + r = (2.0 * r + (f / r / r)) / 3.0; + } +#endif + return DBL2NUM(r); } /* diff --git a/test/ruby/test_math.rb b/test/ruby/test_math.rb index f226287442..5cc12bcfeb 100644 --- a/test/ruby/test_math.rb +++ b/test/ruby/test_math.rb @@ -202,6 +202,7 @@ class TestMath < Test::Unit::TestCase check(3, Math.cbrt(27)) check(-0.1, Math.cbrt(-0.001)) assert_nothing_raised { assert_infinity(Math.cbrt(1.0/0)) } + assert_operator(Math.cbrt(1.0 - Float::EPSILON), :<=, 1.0) end def test_frexp