Permalink
Browse files

Fixed #4016 (false positive: incorrectLogicOperator)

  • Loading branch information...
danmar committed Aug 14, 2012
1 parent e534ee0 commit 1601baa97496d23a0ba6f0ca3a487548e26e00ed
Showing with 21 additions and 2 deletions.
  1. +18 −2 lib/mathlib.cpp
  2. +1 −0 lib/mathlib.h
  3. +2 −0 test/testmathlib.cpp
View
@@ -198,15 +198,31 @@ std::string MathLib::add(const std::string & first, const std::string & second)
if (MathLib::isInt(first) && MathLib::isInt(second)) {
return toString<bigint>(toLongNumber(first) + toLongNumber(second));
}
- return toString<double>(toDoubleNumber(first) + toDoubleNumber(second));
+
+ double d1 = toDoubleNumber(first);
+ double d2 = toDoubleNumber(second);
+ while (d1 > 100000.0 * d2 && toString<double>(d1+d2)==first)
+ d2 *= 10.0;
+ while (d2 > 100000.0 * d1 && toString<double>(d1+d2)==second)
+ d1 *= 10.0;
+
+ return toString<double>(d1 + d2);
}
std::string MathLib::subtract(const std::string &first, const std::string &second)
{
if (MathLib::isInt(first) && MathLib::isInt(second)) {
return toString<bigint>(toLongNumber(first) - toLongNumber(second));
}
- return toString<double>(toDoubleNumber(first) - toDoubleNumber(second));
+
+ double d1 = toDoubleNumber(first);
+ double d2 = toDoubleNumber(second);
+ while (d1 > 100000.0 * d2 && toString<double>(d1-d2)==first)
+ d2 *= 10.0;
+ while (d2 > 100000.0 * d1 && toString<double>(d1-d2)==second)
+ d1 *= 10.0;
+
+ return toString<double>(d1 - d2);
}
std::string MathLib::divide(const std::string &first, const std::string &second)
View
@@ -39,6 +39,7 @@ class CPPCHECKLIB MathLib {
template<typename T>
static std::string toString(const T &d) {
std::ostringstream result;
+ result.precision(8);
result << d;
if (isNullValue(result.str()))
return std::string("0");
View
@@ -87,6 +87,7 @@ class TestMathLib : public TestFixture {
ASSERT_EQUALS("-1" , MathLib::add("0", "-1"));
ASSERT_EQUALS("1" , MathLib::add("1", "0"));
ASSERT_EQUALS("0" , MathLib::add("0", "0."));
+ ASSERT_EQUALS("1.0000001" , MathLib::add("1", "0.00000001")); // #4016
// subtraction
ASSERT_EQUALS("254", MathLib::subtract("0xff", "1"));
@@ -96,6 +97,7 @@ class TestMathLib : public TestFixture {
ASSERT_EQUALS("1" , MathLib::subtract("0", "-1"));
ASSERT_EQUALS("1" , MathLib::subtract("1", "0"));
ASSERT_EQUALS("0" , MathLib::subtract("0", "0."));
+ ASSERT_EQUALS("0.99999999" , MathLib::subtract("1", "0.00000001")); // #4016
// multiply
ASSERT_EQUALS("-0.003" , MathLib::multiply("-1e-3", "3"));

0 comments on commit 1601baa

Please sign in to comment.