From c27d3438ebd1fea4a02c86a9f346844e7cd6c6f3 Mon Sep 17 00:00:00 2001 From: Yegor Kozlov Date: Fri, 1 Oct 2010 12:02:52 +0000 Subject: [PATCH] improved rounding in MathX.mod, see Bugzilla 50033 git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1003504 13f79535-47bb-0310-9956-ffa450edef68 --- src/documentation/content/xdocs/status.xml | 1 + .../poi/hssf/record/formula/functions/MathX.java | 11 +++-------- .../hssf/record/formula/functions/TestMathX.java | 14 ++++++++++++++ 3 files changed, 18 insertions(+), 8 deletions(-) diff --git a/src/documentation/content/xdocs/status.xml b/src/documentation/content/xdocs/status.xml index 1b023b21db..27aa73f5fd 100644 --- a/src/documentation/content/xdocs/status.xml +++ b/src/documentation/content/xdocs/status.xml @@ -34,6 +34,7 @@ + 50033 - Improved rounding in MOD Generate SHA1 hashes of distribution files, alongside existing MD5 ones diff --git a/src/java/org/apache/poi/hssf/record/formula/functions/MathX.java b/src/java/org/apache/poi/hssf/record/formula/functions/MathX.java index f51821d042..600214662b 100644 --- a/src/java/org/apache/poi/hssf/record/formula/functions/MathX.java +++ b/src/java/org/apache/poi/hssf/record/formula/functions/MathX.java @@ -17,6 +17,7 @@ package org.apache.poi.hssf.record.formula.functions; + /** * @author Amol S. Deshmukh < amolweb at ya hoo dot com > * This class is an extension to the standard math library @@ -349,21 +350,15 @@ final class MathX { result = Double.NaN; } else if (sign(n) == sign(d)) { - double t = Math.abs(n / d); - t = t - (long) t; - result = sign(d) * Math.abs(t * d); + result = n % d; } else { - double t = Math.abs(n / d); - t = t - (long) t; - t = Math.ceil(t) - t; - result = sign(d) * Math.abs(t * d); + result = ((n % d) + d) % d; } return result; } - /** * inverse hyperbolic cosine * @param d diff --git a/src/testcases/org/apache/poi/hssf/record/formula/functions/TestMathX.java b/src/testcases/org/apache/poi/hssf/record/formula/functions/TestMathX.java index 783294e9d3..a88f011e7b 100644 --- a/src/testcases/org/apache/poi/hssf/record/formula/functions/TestMathX.java +++ b/src/testcases/org/apache/poi/hssf/record/formula/functions/TestMathX.java @@ -292,6 +292,20 @@ public class TestMathX extends AbstractNumericTestCase { } public void testMod() { + + //example from Excel help + assertEquals(1.0, MathX.mod(3, 2)); + assertEquals(1.0, MathX.mod(-3, 2)); + assertEquals(-1.0, MathX.mod(3, -2)); + assertEquals(-1.0, MathX.mod(-3, -2)); + + assertEquals((double) 1.4, MathX.mod(3.4, 2)); + assertEquals((double) -1.4, MathX.mod(-3.4, -2)); + assertEquals((double) 0.6000000000000001, MathX.mod(-3.4, 2.0));// should actually be 0.6 + assertEquals((double) -0.6000000000000001, MathX.mod(3.4, -2.0));// should actually be -0.6 + + // Bugzilla 50033 + assertEquals(1.0, MathX.mod(13, 12)); } public void testNChooseK() { -- 2.39.5