sui icon indicating copy to clipboard operation
sui copied to clipboard

[rfc][sui framework] u64 module for better math support

Open sblackshear opened this issue 2 years ago • 3 comments

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.

sblackshear avatar Dec 13 '22 01:12 sblackshear

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)

vercel[bot] avatar Dec 13 '22 01:12 vercel[bot]

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/

kklas avatar Dec 16 '22 11:12 kklas

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.

github-actions[bot] avatar Feb 15 '23 02:02 github-actions[bot]

Closing as stale. Raised some of the questions from here internally.

damirka avatar Jun 28 '24 10:06 damirka