Feat/mul div - #54
Conversation
| /// Panics if the result overflows a u256 | ||
| pub fn mul_div_256(a: u256, b: u256, denominator: u256) -> u256 { | ||
| match is_zero_256(denominator) { | ||
| true => 0, |
There was a problem hiding this comment.
Shouldn't we panic if we divide by 0?
There was a problem hiding this comment.
I agree that panicking on division by zero would be less error-prone, but the jet's division functions don't panic on division by zero, so here it feels more like the default behavior
There was a problem hiding this comment.
We had a discussion on a call with @roconnor-blockstream about this behavior, which other people found unusual or surprising. I think it has to do with some functional programming conventions related to wanting functions to be total when possible. I don't know that he necessarily felt that all library functions written using the jet needed to replicate the behavior, but I don't remember his exact position about this.
I think @apoelstra is also familiar with this discussion and might be able to weigh in.
moved arithmetic section for u128 and u256 to be consistent with other sections
LesterEvSe
left a comment
There was a problem hiding this comment.
Also let's add more tests to cover new u512 division functionality.
- Force entry into
algorithm_d_512_256:
a = generate_u256(2^128, U256::MAX)
b = generate_u256(2^128, U256::MAX)
result_high = high 256 bits of a.full_mul(b)
c = generate_u256(max(2^128, result_high + 1), U256::MAX)Guarantees result_high != 0 and denom_high != 0.
- Add two
normalize_to_threshold_512_127tests.
2.1.norm == 1. Forces the divisor's top bit to already be set:
a = generate_u256(2^128, U256::MAX)
b = generate_u256(2^128, U256::MAX)
result_high = high 256 bits of a.full_mul(b)
c = generate_u256(max(2^255, result_high + 1), U256::MAX)2.2. norm > 1. Forces the divisor's top bit to be clear:
a = generate_u256(2^128, U256::MAX)
b = generate_u256(2^128, 2^192)
result_high = high 256 bits of a.full_mul(b) // < 2^192, well under the 2^255 ceiling
c = generate_u256(max(2^128, result_high + 1), 2^255 - 1)-
Same
a, bas (1), butc = result_high + 1. -
Exact division with
remainder == 0. Seta = cfor somecin range[2^128, U256::MAX], pickbasa*b >= 2^256. -
Minimal
denom_high:
a = generate_u256(2^128, 2^129)
b = generate_u256(2^128, 2^129)
result_high = high 256 bits of a.full_mul(b) // in {1, 2, 3}
c = generate_u256(max(2^128, result_high + 1), 2^129 - 1)
Uh oh!
There was an error while loading. Please reload this page.