-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Faster signed multiplication #103
Comments
oscbyspro
changed the title
Better signed
Faster signed multiplication
May 5, 2023
multipliedReportingOverflow(by:)
|
The following assertions test all overflowing signed paths: ANKAssertMultiplication(T.max, T( 1), T.max, T( 0), false)
ANKAssertMultiplication(T.max, T(-1), T.min + T(1), T(-1), false)
ANKAssertMultiplication(T.min, T( 1), T.min, T(-1), false)
ANKAssertMultiplication(T.min, T(-1), T.min, T( 0), true )
ANKAssertMultiplication(T.max, T( 2), T(-2), T( 0), true )
ANKAssertMultiplication(T.max, T(-2), T( 2), T(-1), true )
ANKAssertMultiplication(T.min, T( 2), T( 0), T(-1), true )
ANKAssertMultiplication(T.min, T(-2), T( 0), T( 1), true ) |
I find this rewrite, which leverages if !Self.isSigned {
overflow = !(product.high.matches(repeating: false)) // 🚀
} else if self.isLessThanZero == amount.isLessThanZero {
// overflow = product > Self.max, but more efficient
overflow = !(product.high.matches(repeating: false) && !product.low.mostSignificantBit) // 🏎️
} else {
// overflow = product < Self.min, but more efficient
overflow = !(product.high.matches(repeating: true ) && product.low.mostSignificantBit) && product.high.mostSignificantBit // 🏎️
} Alternatively: if !Self.isSigned {
overflow = !(product.high.isZero) // 🚀
} else if self.isLessThanZero == amount.isLessThanZero {
// overflow = product > Self.max, but more efficient
overflow = !(product.high.isZero && !product.low.mostSignificantBit) // 🏎️
} else {
// overflow = product < Self.min, but more efficient
overflow = !(product.high.isFull && product.low.mostSignificantBit) && product.high.mostSignificantBit // 🏎️
} |
oscbyspro
added a commit
that referenced
this issue
May 6, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Signed multiplication is currently much slower than unsigned, mostly because the signed overflow check is snail-paced.
I believe the following is a faster, allocationless, version of the same comparsion. Although, I may have to add tests for it.
The idea is to only check bits that are significant for detecting overflow.
The text was updated successfully, but these errors were encountered: