Skip to content

Commit 0ec8de5

Browse files
algo.3 oppsite of real numbers (#13)
1 parent 0bd5a9a commit 0ec8de5

File tree

4 files changed

+52
-0
lines changed

4 files changed

+52
-0
lines changed

src/epsilon/r.hpp

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,15 @@ constexpr r<C> add(r<C> x, r<C> y) {
3535
};
3636
}
3737

38+
template <container C>
39+
constexpr r<C> opp(r<C> x) {
40+
return [x = std::move(x)](unsigned int n) -> coro::lazy<z<C>> {
41+
auto xn = co_await x(n);
42+
negate(xn);
43+
co_return xn;
44+
};
45+
}
46+
3847
} // namespace epx
3948

4049
#endif // EPSILON_INC_R_HPP

src/epsilon/z.hpp

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,9 @@ constexpr z<C>& normalize(z<C>& num) noexcept {
133133

134134
template <container C>
135135
constexpr z<C>& negate(z<C>& num) noexcept {
136+
if (is_zero(num)) {
137+
return num;
138+
}
136139
num.sgn = is_positive(num) ? sign::negative : sign::positive;
137140
return num;
138141
}

src/ut/r_tests.cpp

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,4 +98,24 @@ TEST(r_tests, add) {
9898
}
9999
}
100100

101+
TEST(r_tests, opp) {
102+
{
103+
auto x = epx::make_q(stosz("0"), stosz("1"));
104+
auto expr = epx::opp(x);
105+
EXPECT_EQ("0", epx::to_string(expr, 0));
106+
EXPECT_EQ("0.00000", epx::to_string(expr, 5));
107+
}
108+
{
109+
auto x = epx::make_q(stosz("1"), stosz("1"));
110+
auto expr = epx::opp(x);
111+
EXPECT_EQ("-1", epx::to_string(expr, 0));
112+
EXPECT_EQ("-1.00000", epx::to_string(expr, 5));
113+
}
114+
{
115+
auto x = epx::make_q(stosz("-1"), stosz("7"));
116+
auto expr = epx::opp(x);
117+
EXPECT_EQ("0.14285714285714285714286", epx::to_string(expr, 23));
118+
}
119+
}
120+
101121
} // namespace epxut

src/ut/z_tests.cpp

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,26 @@ TEST(z_tests, normalize) {
6161
}
6262
}
6363

64+
TEST(z_tests, negate) {
65+
{
66+
sz zero;
67+
epx::negate(zero);
68+
EXPECT_TRUE(epx::is_zero(zero));
69+
}
70+
{
71+
sz num = {.digits = {1}};
72+
sz expected = {.digits = {1}, .sgn = epx::sign::negative};
73+
epx::negate(num);
74+
EXPECT_EQ(expected, num);
75+
}
76+
{
77+
sz num = {.digits = {1}, .sgn = epx::sign::negative};
78+
sz expected = {.digits = {1}};
79+
epx::negate(num);
80+
EXPECT_EQ(expected, num);
81+
}
82+
}
83+
6484
TEST(z_tests, add) {
6585
{
6686
sz zero, one{.digits = {1}}, minus_one{.digits = {1}, .sgn = epx::sign::negative};

0 commit comments

Comments
 (0)