openMSX
FixedPoint_test.cc
Go to the documentation of this file.
1#include "catch.hpp"
2#include "FixedPoint.hh"
3#include "narrow.hh"
4
5using namespace openmsx;
6
7template<unsigned BITS>
8static void check(const FixedPoint<BITS>& fp, int expectedRaw)
9{
10 REQUIRE(fp.getRawValue() == expectedRaw);
11 int i = expectedRaw >> BITS;
12 unsigned fi = expectedRaw & ((1 << BITS) - 1);
13 float ff = float (fi) / (1 << BITS);
14 double fd = double(fi) / (1 << BITS);
15 float f = narrow_cast<float >(i) + ff;
16 double d = narrow_cast<double>(i) + fd;
17 CHECK(fp.toInt() == i);
18 CHECK(fp.toFloat() == f);
19 CHECK(fp.toDouble() == d);
20 CHECK(fp.fractAsInt() == fi);
21 CHECK(fp.fractionAsFloat() == ff);
22 CHECK(fp.fractionAsDouble() == fd);
23 CHECK(fp.floor().getRawValue() == (i << BITS));
24 CHECK(fp.fract().getRawValue() == int(fi));
25}
26
27TEST_CASE("FixedPoint")
28{
29 FixedPoint<2> a(10 ); check(a, 40);
30 FixedPoint<2> b(3.5f); check(b, 14);
31 FixedPoint<2> c(1.75); check(c, 7);
32 FixedPoint<7> d(c); check(d, 224); // more fractional bits
33 FixedPoint<1> e(d); check(e, 3); // less fractional bits
34
35 check(FixedPoint<3>::roundRatioDown(2, 3), 5); // 2/3 ~= 5/8
36
37 CHECK(a.divAsInt(b) == 2);
38 CHECK(b.divAsInt(a) == 0);
39 CHECK(b.divAsInt(c) == 2);
40
41 check(a + b, 54);
42 check(a + c, 47);
43 check(b + c, 21);
44
45 check(a - b, 26); check(b - a, -26);
46 check(a - c, 33); check(c - a, -33);
47 check(b - c, 7); check(c - b, -7);
48
49 check(a * b, 140);
50 check(a * c, 70);
51 check(b * c, 24);
52 check(a * 2, 80);
53 check(b * -3, -42);
54 check(c * 4, 28);
55
56 check(a / b, 11); check(b / a, 1);
57 check(a / c, 22); check(c / a, 0);
58 check(b / c, 8); check(c / b, 2);
59 check(a / -5, -8);
60 check(b / 4, 3);
61 check(c / -3, -2);
62
63 check(a << 1, 80); check(a >> 3, 5);
64 check(b << 2, 56); check(b >> 2, 3);
65 check(c << 3, 56); check(c >> 1, 3);
66
67 CHECK(a == a); CHECK(!(a != a));
68 CHECK(a != b); CHECK(!(a == b));
69 CHECK(b < a); CHECK(!(b >= a));
70 CHECK(b <= a); CHECK(!(b > a));
71 CHECK(a > b); CHECK(!(a <= b));
72 CHECK(a >= b); CHECK(!(a < b));
73
74 a += b; check(a, 54);
75 c -= a; check(c, -47);
76
77 a.addQuantum(); check(a, 55);
78 b.addQuantum(); check(b, 15);
79 c.addQuantum(); check(c, -46);
80}
TEST_CASE("FixedPoint")
A fixed point number, implemented by a 32-bit signed integer.
Definition FixedPoint.hh:16
constexpr int divAsInt(FixedPoint other) const
Returns the result of a division between this fixed point number and another, rounded towards zero.
constexpr int getRawValue() const
constexpr void addQuantum()
Increase this value with the smallest possible amount.
CHECK(m3==m3)
constexpr unsigned BITS
Definition CacheLine.hh:6
This file implemented 3 utility functions:
Definition Autofire.cc:11