Skip to content

Commit cd64cb2

Browse files
committed
add binary search
1 parent c624136 commit cd64cb2

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

src/CurveLib.sol

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,4 +111,32 @@ library CurveLib {
111111
function abs(int256 x) internal pure returns (uint256) {
112112
return uint256(x >= 0 ? x : -x);
113113
}
114+
115+
function binarySearch(
116+
uint256 y,
117+
uint256 px,
118+
uint256 py,
119+
uint256 x0,
120+
uint256 y0,
121+
uint256 c,
122+
uint256 xMin,
123+
uint256 xMax
124+
) internal pure returns (uint256) {
125+
if (xMin < 1) {
126+
xMin = 1;
127+
}
128+
while (xMin < xMax) {
129+
uint256 xMid = (xMin + xMax) / 2;
130+
uint256 fxMid = f(xMid, px, py, x0, y0, c);
131+
if (y >= fxMid) {
132+
xMax = xMid;
133+
} else {
134+
xMin = xMid + 1;
135+
}
136+
}
137+
if (y < f(xMin, px, py, x0, y0, c)) {
138+
xMin += 1;
139+
}
140+
return xMin;
141+
}
114142
}

0 commit comments

Comments
 (0)