From 653ebf6675f42dde3cbda1fc088f84a7264ec013 Mon Sep 17 00:00:00 2001 From: batsumaru <> Date: Sun, 9 Aug 2026 17:26:31 +0900 Subject: Added fp_t division --- src/fixed_point.cpp | 29 +++++++++++++++++++++++------ 1 file changed, 23 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/fixed_point.cpp b/src/fixed_point.cpp index 847a5f7..8b4b937 100644 --- a/src/fixed_point.cpp +++ b/src/fixed_point.cpp @@ -1,22 +1,39 @@ #include "fixed_point.h" +#include +#include fp_t fp_t::operator+(const fp_t& other) const { - return {(int32_t)((uint32_t)raw + (uint32_t)other.raw)}; + return {(std::int32_t)((std::uint32_t)raw + (std::uint32_t)other.raw)}; } fp_t fp_t::operator-(const fp_t& other) const { - return {(int32_t)((uint32_t)raw - (uint32_t)other.raw)}; + return {(std::int32_t)((std::uint32_t)raw - (std::uint32_t)other.raw)}; } fp_t fp_t::operator*(const fp_t& other) const { - int32_t result; - int64_t temp; - temp = (int64_t)raw * (int64_t)other.raw; + std::int32_t result; + std::int64_t temp; + temp = (std::int64_t)raw * (std::int64_t)other.raw; temp += fp_t::K; - result = (int32_t)(temp >> fp_t::Q); + result = (std::int32_t)(temp >> fp_t::Q); return {result}; } +fp_t fp_t::operator/(const fp_t& other) const { + if (other.raw == 0) { + std::fprintf(stderr, "fp_t: division by zero\n"); + std::abort(); + } + std::int64_t temp = (std::int64_t)raw << fp_t::Q; + + if ((temp >= 0 && other.raw >= 0) || (temp < 0 && other.raw < 0)) { + temp += (other.raw / 2); + } else { + temp -= (other.raw / 2); + } + return {(std::int32_t)(temp / other.raw)}; +} + bool fp_t::operator==(const fp_t& other) const { return raw == other.raw; } -- cgit v1.3