Skip to content

Commit

Permalink
Avoid division by zero with fixed-point DIV and LOG
Browse files Browse the repository at this point in the history
  • Loading branch information
Rangi42 committed Dec 30, 2024
1 parent afaaf0a commit 198b6f1
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
11 changes: 9 additions & 2 deletions src/asm/fixpoint.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,11 @@ int32_t fix_Mul(int32_t i, int32_t j, int32_t q) {
}

int32_t fix_Div(int32_t i, int32_t j, int32_t q) {
return double2fix(fix2double(i, q) / fix2double(j, q), q);
double dividend = fix2double(i, q);
double divisor = fix2double(j, q);
if (divisor == 0.0)
return dividend < 0 ? INT32_MIN : dividend > 0 ? INT32_MAX : 0;
return double2fix(dividend / divisor, q);
}

int32_t fix_Mod(int32_t i, int32_t j, int32_t q) {
Expand All @@ -85,7 +89,10 @@ int32_t fix_Pow(int32_t i, int32_t j, int32_t q) {
}

int32_t fix_Log(int32_t i, int32_t j, int32_t q) {
return double2fix(log(fix2double(i, q)) / log(fix2double(j, q)), q);
double divisor = log(fix2double(j, q));
if (divisor == 0.0)
return INT32_MAX;
return double2fix(log(fix2double(i, q)) / divisor, q);
}

int32_t fix_Round(int32_t i, int32_t q) {
Expand Down
3 changes: 3 additions & 0 deletions test/asm/math.asm
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ ENDM

assert LOG(100.0, 10.0) == 2.0
assert LOG(256.0, 2.0) == 8.0
assert LOG(10.0, 1.0) == $7fff_ffff ; +inf
assert LOG(0.0, 2.71828) == $8000_0000 ; -inf
assert LOG(-1.0, 2.71828) == 0 ; nan

assert ROUND(1.5) == 2.0
assert ROUND(-1.5) == -2.0
Expand Down

0 comments on commit 198b6f1

Please sign in to comment.