Skip to content

Instantly share code, notes, and snippets.

@k06a k06a/log_2_rand_0_1.sol
Last active Aug 16, 2019

Embed
What would you like to do?
log_2_rand_0_1
/*
* ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.
* Author: Mikhail Vladimirov <mikhail.vladimirov@gmail.com>
*/
pragma solidity ^0.5.7;
/**
* Modified version of this code:
* https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L366
*
* Modifications:
* - input considered as random and trunctaed to (0..1] random value
* - returning value multiplied by 1e18, precision decreased to 6 decimals digits
*/
contract ABDKMath64x64_Modified {
//
// Example 1:
// log2(0.19891989) => -2.3297405564
// 3669424302000455899 => 2329741477966308593
//
// 1. 0.19891989 * 2^64 => 3669424302000455899
// 2. log_2_rand_0_1(3669424302000455899) => 2329741477966308593
// 3. 2^(-2329741477966308593/1e18) => 0,1989197629 (with precision 1e-6)
//
function log_2_rand_0_1(uint256 x) public pure returns (uint256) {
x &= 0xFFFFFFFFFFFFFFFF;
require(x > 0);
uint256 a = 63;
while ((x >> a) == 0) {
a--;
}
uint256 result = a - 64 << 64;
uint256 ux = x << 127 - a;
for (uint256 bit = 63; bit > 43; bit--) {
ux *= ux;
result |= ((ux >> 255) << bit);
ux >>= 127 + (ux >> 255);
}
return uint256((-int256(result) * 1e18) >> 64);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.