forked from platypus-finance/core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TestDSMath.sol
59 lines (49 loc) · 1.67 KB
/
TestDSMath.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// DO NOT DEPLOY TO MAINNET
// ONLY FOR TESTING PURPOSES
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.9;
import '../libraries/DSMath.sol';
contract TestDSMath {
using DSMath for uint256;
uint256 public constant WAD = 10**18;
uint256 public constant RAY = 10**27;
//rounds to zero if x*y < WAD / 2
function wmul(uint256 x, uint256 y) external pure returns (uint256) {
return ((x * y) + (WAD / 2)) / WAD;
}
//rounds to zero if x*y < WAD / 2
function wdiv(uint256 x, uint256 y) public pure returns (uint256) {
return ((x * WAD) + (y / 2)) / y;
}
function reciprocal(uint256 x) external pure returns (uint256) {
return wdiv(WAD, x);
}
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
//
function rpow(uint256 x, uint256 n) external pure returns (uint256 z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
//rounds to zero if x*y < WAD / 2
function rmul(uint256 x, uint256 y) public pure returns (uint256 z) {
z = ((x * y) + (RAY / 2)) / RAY;
}
}