solid中带小数的指数/幂

  • 本文关键字:指数 小数 solid solidity
  • 更新时间 :
  • 英文 :


我想在固体中做这个指数运算:

3^0.1 = 1.11

我知道,在固体是不可能使用十进制值,所以我怎么能解决这个操作?

我试图用WEI来实现这一点,但我不能,因为结果太大了。

任何想法?

您可以使用ABDKMath库,或者您可以直接乘以更高的指数来表示浮点数(例如:10000可以表示100%)

pragma solidity ^0.8.0;
import "https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol";
contract Test {
function power() public pure returns (uint) {
// Represent 3 as a fixed-point number.
int128 three = ABDKMath64x64.fromUInt(3);
// Calculate ln(3)
int128 lnThree = ABDKMath64x64.ln(three);
// Represent 0.1 as a fixed-point number.
int128 oneTenth = ABDKMath64x64.divu(1, 10);
// Calculate 0.1 * ln(3)
int128 product = ABDKMath64x64.mul(lnThree, oneTenth);
// Calculate e^(0.1*ln(3))
int128 result = ABDKMath64x64.exp(product);
// Multiply by 10^5 to keep 5 decimal places
result = ABDKMath64x64.mul(result, ABDKMath64x64.fromUInt(10**5));
// Convert the fixed-point result to a uint and return it.
return ABDKMath64x64.toUInt(result);
}
}

有一个链接到它们的自述文件:https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.md

最新更新