Skip to content

Commit

Permalink
Merge pull request #13 from Rudxain/abs_ratio
Browse files Browse the repository at this point in the history
add abs-ratio
  • Loading branch information
Rudxain committed Jun 19, 2024
2 parents 5653e6f + 8c4317c commit b32fcb0
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions wiki/Absolute_ratio.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# Absolute ratio
Defined as the [quotient](https://en.wikipedia.org/wiki/Quotient) between the maximum and minimum [absolute-values](https://en.wikipedia.org/wiki/Absolute_value) of both input arguments.

## Applications
It can be used to guarantee that integer division is always greater than 0, which "preserves" the information of the operands.

## Implementation
[PFP](https://en.wikipedia.org/wiki/Pure_functional_programming)-style code in both Python and TypeScript, respectively:
```py
from typing import Final, Callable
# there's `TypeVar` but `//` forces us to `def` 2 APIs

fabs_ratio: Final[Callable[[float, float], float]] = lambda x, y, /: (
lambda x, y: max(x, y) / min(x, y)
)(abs(x), abs(y))

iabs_ratio: Final[Callable[[int, int], int]] = lambda x, y, /: (
lambda x, y: max(x, y) // min(x, y)
)(abs(x), abs(y))
```
```ts
type numeric = number | bigint

const
max = <T extends numeric,>(x: T, y: T) =>
x < y ? y : x,
min = <T extends numeric,>(x: T, y: T) =>
x > y ? y : x,
abs = <T extends numeric,>(x: T) =>
x < 0 ? -x as T : x

const abs_ratio = <T extends numeric,>(x: T, y: T) =>
(max(abs(x), abs(y)) / min(abs(x), abs(y))) as T
```

## See also
[Rust `lib`](https://github.com/Rudxain/abs_ratio/blob/main/src/lib.rs)

0 comments on commit b32fcb0

Please sign in to comment.