sui
sui copied to clipboard
[rfc][sui framework] u64 module for better math support
Trying out a new style of math support. Want to align on the API's we should provide for each integer type first, then we can create similar modules for the other integer types.
The latest updates on your projects. Learn more about Vercel for Git ↗︎
| Name | Status | Preview | Comments | Updated |
|---|---|---|---|---|
| wallet-adapter | ❌ Failed (Inspect) | Dec 13, 2022 at 1:20AM (UTC) |
muldiv would also be nice to have. I use it a lot in my modules (and copy paste it every time).
/// Calculates (a * b) / c. Aborts if the result doesn't fit into u64.
fun muldiv(a: u64, b: u64, c: u64): u64 {
(((a as u128) * (b as u128)) / (c as u128) as u64)
}
It preserves precision when you're doing (a * b) / c where a * b doesn't fit into u64 but (a * b) / c does, which I found to be quite often (notice it's applicable any time you have (a / c) * b or a * (b / c), i.e. any time a / c or b / c < 1 e.g. when taking a percentage of something). See this for some real life usages.
Btw there's a really cool way to calculate u256 muldiv using only u256 registers with math tricks: https://2π.com/21/muldiv/
This PR is stale because it has been open 60 days with no activity. Remove stale label or comment or this will be closed in 7 days.
Closing as stale. Raised some of the questions from here internally.