Search code examples
ethereumsoliditysmartcontracts

Exponential equation in Solidity


I'm trying to recreate the following equation in solidity.

enter image description here

I know that solidity does not have the concept of floating point numbers so I am trying to use the ABDKMathQuad library. Unfortunately I've not had much success (I've not even been able to multiply two floating point numbers together)

bytes8 a = 0x0000000000018000;  // 1.8
bytes8 b = 0x0000000000024000;  // 2.4
bytes16 a_16 = ABDKMathQuad.fromDouble(a);
bytes16 b_16 = ABDKMathQuad.fromDouble(b);
bytes16 _temp = ABDKMathQuad.mul(a_16, b_16);
bytes8 result = ABDKMathQuad.toDouble(_temp);

Even

bytes16 a = 0x00000000000000000000000000018000;  // 1.8
bytes16 a = 0x00000000000000000000000000024000;  // 2.4
bytes16 _temp = ABDKMathQuad.mul(a, b);

Doesn't seem to yield anything.

Where am I going wrong?


Solution

  • I managed to solve this using Avatar Paul Razvan Berg' brilliant PRBMath library.

    import "prb-math/contracts/PRBMathSD59x18.sol";
    
    contract SimpleContract {
    
        using PRBMathSD59x18 for int256;
    
        function exponential_function(int256 x) public view returns (int256) {
            int256 z = 90000000000000000;      // 0.09
            int256 a = 200000000000000000;     // 0.2
            int256 b = 1080000000000000000;    // 1.08
            int256 c = -10000000000000000000;  // -10
            int256 d = 100000000000000000;     // 0.1
            int256 _x = x * 1000000000000000000;
            int256 outcome = PRBMathSD59x18.mul(a, b.pow(PRBMathSD59x18.mul(z, _x) + c)) + d;
            return outcome;
        }
    }
    

    (Though as noted in his repo the pow function is about four times more expensive than the one in ABDKMath64x64)