Solidity Math – Performing Logarithm Operations

solidity

what is the most efficient way to compute a logarithm in solidity? Is there a library that implements it or a built in function?

Best Answer

Though there's no current implementation (and I couldn't see one in the dapp-bin either), you could implement your own using a Taylor Series, as suggested by Vitalik in this old Reddit thread.

For the example in the thread, it effectively comes down to something like the following:

 x = msg.data[0]
 LOG = 0
 while x >= 1500000:
     LOG = LOG + 405465
     x = x * 2 / 3
 x = x - 1000000
 y = x
 i = 1
 while i < 10:
      LOG = LOG + (y / i)
      i = i + 1
      y = y * x / 1000000
      LOG = LOG - (y / i)
      i = i + 1
      y = y * x / 1000000
return(LOG)

Bear in mind the number of steps and the associated gas cost...