[前][次][番号順一覧][スレッド一覧]

ruby-changes:43824

From: nobu <ko1@a...>
Date: Mon, 15 Aug 2016 11:00:05 +0900 (JST)
Subject: [ruby-changes:43824] nobu:r55897 (trunk): numeric.c: round_to_nearest

nobu	2016-08-15 10:59:58 +0900 (Mon, 15 Aug 2016)

  New Revision: 55897

  https://svn.ruby-lang.org/cgi-bin/viewvc.cgi?view=revision&revision=55897

  Log:
    numeric.c: round_to_nearest
    
    * numeric.c (round_to_nearest): extract and reduce for platforms
      where round is not available.

  Modified files:
    trunk/numeric.c
Index: numeric.c
===================================================================
--- numeric.c	(revision 55896)
+++ numeric.c	(revision 55897)
@@ -92,6 +92,31 @@ round(double x) https://github.com/ruby/ruby/blob/trunk/numeric.c#L92
 }
 #endif
 
+static double
+round_to_nearest(double x, double s)
+{
+    double f, xs = x * s;
+
+#ifdef HAVE_ROUND
+    f = round(xs);
+#endif
+    if (x > 0) {
+#ifndef HAVE_ROUND
+	f = floor(xs);
+#endif
+	if ((double)((f + 0.5) / s) <= x) f += 1;
+	x = f;
+    }
+    else {
+#ifndef HAVE_ROUND
+	f = ceil(xs);
+#endif
+	if ((double)((f - 0.5) / s) >= x) f -= 1;
+	x = f;
+    }
+    return x;
+}
+
 static VALUE fix_uminus(VALUE num);
 static VALUE fix_mul(VALUE x, VALUE y);
 static VALUE fix_lshift(long, unsigned long);
@@ -2089,13 +2114,7 @@ flo_round(int argc, VALUE *argv, VALUE n https://github.com/ruby/ruby/blob/trunk/numeric.c#L2114
     }
     if (float_invariant_round(number, ndigits, &num)) return num;
     f = pow(10, ndigits);
-    x = round(number * f);
-    if (x > 0) {
-	if ((double)((x + 0.5) / f) <= number) x += 1;
-    }
-    else {
-	if ((double)((x - 0.5) / f) >= number) x -= 1;
-    }
+    x = round_to_nearest(number, f);
     return DBL2NUM(x / f);
 }
 

--
ML: ruby-changes@q...
Info: http://www.atdot.net/~ko1/quickml/

[前][次][番号順一覧][スレッド一覧]