From 58d0577a027646071da0b4d03feede8f12ee7c79 Mon Sep 17 00:00:00 2001 From: Martin Janiczek Date: Thu, 23 Nov 2023 01:34:40 +0100 Subject: [PATCH] AK: Fix bugs in Complex += -= + - * / operators There were two issues: 1) the C+=R and C-=R operators expected arithmetic types to have .real() 2) the R+C, R-C, R*C and R/C operators applied the operation in wrong order (did C+R, C-R, C*R and C/R instead). This wouldn't matter for + and * which are commutative, but is incorrect for - and /. --- AK/Complex.h | 12 ++++++------ Tests/AK/TestComplex.cpp | 26 ++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/AK/Complex.h b/AK/Complex.h index a7fd830093..e9963d31f6 100644 --- a/AK/Complex.h +++ b/AK/Complex.h @@ -83,7 +83,7 @@ public: template constexpr Complex operator+=(U const& x) { - m_real += x.real(); + m_real += x; return *this; } @@ -98,7 +98,7 @@ public: template constexpr Complex operator-=(U const& x) { - m_real -= x.real(); + m_real -= x; return *this; } @@ -224,7 +224,7 @@ private: // reverse associativity operators for scalars template -constexpr Complex operator+(U const& b, Complex const& a) +constexpr Complex operator+(U const& a, Complex const& b) { Complex x = a; x += b; @@ -232,7 +232,7 @@ constexpr Complex operator+(U const& b, Complex const& a) } template -constexpr Complex operator-(U const& b, Complex const& a) +constexpr Complex operator-(U const& a, Complex const& b) { Complex x = a; x -= b; @@ -240,7 +240,7 @@ constexpr Complex operator-(U const& b, Complex const& a) } template -constexpr Complex operator*(U const& b, Complex const& a) +constexpr Complex operator*(U const& a, Complex const& b) { Complex x = a; x *= b; @@ -248,7 +248,7 @@ constexpr Complex operator*(U const& b, Complex const& a) } template -constexpr Complex operator/(U const& b, Complex const& a) +constexpr Complex operator/(U const& a, Complex const& b) { Complex x = a; x /= b; diff --git a/Tests/AK/TestComplex.cpp b/Tests/AK/TestComplex.cpp index 5079569d18..4757430024 100644 --- a/Tests/AK/TestComplex.cpp +++ b/Tests/AK/TestComplex.cpp @@ -42,3 +42,29 @@ TEST_CASE(Complex) EXPECT_APPROXIMATE(cexp(Complex(0., 1.) * M_PI).real(), -1.); #endif } + +TEST_CASE(real_operators_regression) +{ + { + auto c = Complex(0., 0.); + c += 1; + EXPECT_EQ(c.real(), 1); + } + { + auto c = Complex(0., 0.); + c -= 1; + EXPECT_EQ(c.real(), -1); + } + { + auto c1 = Complex(1., 1.); + auto c2 = 1 - c1; + EXPECT_EQ(c2.real(), 0); + EXPECT_EQ(c2.imag(), -1); + } + { + auto c1 = Complex(1., 1.); + auto c2 = 1 / c1; + EXPECT_EQ(c2.real(), 0.5); + EXPECT_EQ(c2.imag(), -0.5); + } +}