Created
January 17, 2018 20:09
-
-
Save joejordan/69eb91eb03ec9a3dbd3c06dbd2a19d09 to your computer and use it in GitHub Desktop.
Efficient way to compute the exponentiation of a fraction and an integer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://ethereum.stackexchange.com/a/10432/24989 | |
// Approximate solution using the binomial expansion | |
// The following is a decent, low-cost approximation: | |
// Computes `k * (1+1/q) ^ N`, with precision `p`. The higher | |
// the precision, the higher the gas cost. It should be | |
// something around the log of `n`. When `p == n`, the | |
// precision is absolute (sans possible integer overflows). <edit: NOT true, see comments> | |
// Much smaller values are sufficient to get a great approximation. | |
function fracExp(uint k, uint q, uint n, uint p) returns (uint) { | |
uint s = 0; | |
uint N = 1; | |
uint B = 1; | |
for (uint i = 0; i < p; ++i){ | |
s += k * N / B / (q**i); | |
N = N * (n-i); | |
B = B * (i+1); | |
} | |
return s; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment