Fixed-point arithmetic is a numerical representation that can be used to represent real numbers with a fixed number of digits after the decimal point. It is particularly useful in systems where floating-point precision is limited or when performance is critical, such as in embedded systems.
In C++, fixed-point arithmetic can be implemented using integers and a scaling factor to represent the fixed number of decimal places. Below is an example of how you can implement simple fixed-point arithmetic in C++.
#include
#include
class FixedPoint {
private:
int32_t value; // Underlying integer representation
static const int32_t scale = 10000; // Scale factor (4 decimal places)
public:
FixedPoint(int32_t v) : value(v * scale) {}
FixedPoint(float v) : value(static_cast(v * scale)) {}
// Addition
FixedPoint operator+(const FixedPoint& other) {
return FixedPoint(0, this->value + other.value);
}
// Subtraction
FixedPoint operator-(const FixedPoint& other) {
return FixedPoint(0, this->value - other.value);
}
// Multiplication
FixedPoint operator*(const FixedPoint& other) {
return FixedPoint(0, (this->value * other.value) / scale);
}
// Division
FixedPoint operator/(const FixedPoint& other) {
return FixedPoint(0, (this->value * scale) / other.value);
}
// Conversion to float
float toFloat() const {
return static_cast(value) / scale;
}
private:
// Private constructor for internal use
FixedPoint(int32_t, int32_t v) : value(v) {}
};
int main() {
FixedPoint a(1.2345);
FixedPoint b(2.3456);
FixedPoint c = a + b;
std::cout << "Sum: " << c.toFloat() << std::endl;
return 0;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?