1
0
Fork 0
mirror of https://github.com/LadybirdBrowser/ladybird.git synced 2025-06-09 09:34:57 +09:00

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 /.
This commit is contained in:
Martin Janiczek 2023-11-23 01:34:40 +01:00 committed by Tim Flynn
parent 963a6b3d3d
commit 58d0577a02
Notes: sideshowbarker 2024-07-17 07:38:17 +09:00
2 changed files with 32 additions and 6 deletions

View file

@ -83,7 +83,7 @@ public:
template<AK::Concepts::Arithmetic U>
constexpr Complex<T> operator+=(U const& x)
{
m_real += x.real();
m_real += x;
return *this;
}
@ -98,7 +98,7 @@ public:
template<AK::Concepts::Arithmetic U>
constexpr Complex<T> operator-=(U const& x)
{
m_real -= x.real();
m_real -= x;
return *this;
}
@ -224,7 +224,7 @@ private:
// reverse associativity operators for scalars
template<AK::Concepts::Arithmetic T, AK::Concepts::Arithmetic U>
constexpr Complex<T> operator+(U const& b, Complex<T> const& a)
constexpr Complex<T> operator+(U const& a, Complex<T> const& b)
{
Complex<T> x = a;
x += b;
@ -232,7 +232,7 @@ constexpr Complex<T> operator+(U const& b, Complex<T> const& a)
}
template<AK::Concepts::Arithmetic T, AK::Concepts::Arithmetic U>
constexpr Complex<T> operator-(U const& b, Complex<T> const& a)
constexpr Complex<T> operator-(U const& a, Complex<T> const& b)
{
Complex<T> x = a;
x -= b;
@ -240,7 +240,7 @@ constexpr Complex<T> operator-(U const& b, Complex<T> const& a)
}
template<AK::Concepts::Arithmetic T, AK::Concepts::Arithmetic U>
constexpr Complex<T> operator*(U const& b, Complex<T> const& a)
constexpr Complex<T> operator*(U const& a, Complex<T> const& b)
{
Complex<T> x = a;
x *= b;
@ -248,7 +248,7 @@ constexpr Complex<T> operator*(U const& b, Complex<T> const& a)
}
template<AK::Concepts::Arithmetic T, AK::Concepts::Arithmetic U>
constexpr Complex<T> operator/(U const& b, Complex<T> const& a)
constexpr Complex<T> operator/(U const& a, Complex<T> const& b)
{
Complex<T> x = a;
x /= b;

View file

@ -42,3 +42,29 @@ TEST_CASE(Complex)
EXPECT_APPROXIMATE(cexp(Complex<double>(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);
}
}