How to code logarithm in python(without any libraries)

128 views Asked by At

Yes, I know that you can do:

import math

print(math.log(2, 10))

But I want to do it without using any libraries. Is it even possible?

I could try using:

def log(a, base):
  for x in range(0, base):
    if base ** x == round(a, 5):
      return x

but that would be slow.

2

There are 2 answers

1
Dmitrii Malygin On

Try to use this function:

def log(a, base):
    x = 0
    while a >= base:
        a /= base
        x += 1
    return x
0
Dmitrii Malygin On

You can use the function below. This differs from the previous one by continuous calculation. The parameter settings will affect the calculation speed.

def log(a, base):
    if base <= 1 or a <= 0:
        return None
    elif base == a:
        return 1 
    elif a == 1:
        return 0 
    else:
        lower, upper = 0, a
        while upper - lower > 1e-10:  # some small number
            mid = (lower + upper) / 2
            if base ** mid < a:
                lower = mid
            else:
                upper = mid
        return round(lower, 10)  # accuracy