-
Notifications
You must be signed in to change notification settings - Fork 12.4k
Add sqrt for math #3242
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
Add sqrt for math #3242
Changes from 13 commits
8050d7d
74076e3
98e1358
25950fa
8d5d2d2
55a870d
270e8fc
71ac6df
fa2b258
27d025e
5dde1b8
1a5aee1
0218d35
c940f21
0b157fa
6e1ce42
6c138b2
beaf866
455fcea
abe47be
361fe6b
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -149,4 +149,62 @@ library Math { | |
| } | ||
| return result; | ||
| } | ||
|
|
||
| /** | ||
| * @dev Returns the square root of a number. | ||
|
||
| * | ||
| * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11). | ||
| */ | ||
| function sqrt(uint256 a) internal pure returns (uint256) { | ||
| if (a == 0) { | ||
| return 0; | ||
| } | ||
|
|
||
| // For our first guess, we use the log2 of the square root. We do that by shifting `a` and only counting half | ||
| // of the bits. the partial result produced is a power of two that verifies `result <= sqrt(a) < 2 * result` | ||
|
||
| uint256 result = 1; | ||
| uint256 x = a; | ||
| if (x > 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) { | ||
|
||
| x >>= 128; | ||
| result <<= 64; | ||
| } | ||
| if (x > 0xFFFFFFFFFFFFFFFF) { | ||
| x >>= 64; | ||
| result <<= 32; | ||
| } | ||
| if (x > 0xFFFFFFFF) { | ||
| x >>= 32; | ||
| result <<= 16; | ||
| } | ||
| if (x > 0xFFFF) { | ||
| x >>= 16; | ||
| result <<= 8; | ||
| } | ||
| if (x > 0xFF) { | ||
| x >>= 8; | ||
| result <<= 4; | ||
| } | ||
| if (x > 0xF) { | ||
| x >>= 4; | ||
| result <<= 2; | ||
| } | ||
| if (x > 0x3) { | ||
| result <<= 1; | ||
| } | ||
|
|
||
| // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128, | ||
| // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at | ||
| // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision | ||
| // into the expected uint128 result. | ||
| unchecked { | ||
| result = (result + a / result) >> 1; | ||
| result = (result + a / result) >> 1; | ||
| result = (result + a / result) >> 1; | ||
| result = (result + a / result) >> 1; | ||
| result = (result + a / result) >> 1; | ||
| result = (result + a / result) >> 1; | ||
| result = (result + a / result) >> 1; | ||
| return min(result, a / result); | ||
| } | ||
| } | ||
| } | ||
Uh oh!
There was an error while loading. Please reload this page.