Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get logarithm without math log python

Tags:

math

I'm learning Python and I must do a script that generate the result of the log.

I know that log base x = result

Then I made my code.

def log(x, base):
log_b = 2
while x != int(round(base ** log_b)):
    log_b += 0.01
    print log_b
return int(round(log_b))

But it's works very slowly. I can use other method? thanks!

like image 902
dragon_ball Avatar asked Nov 03 '12 16:11

dragon_ball


People also ask

Is log in Python the natural log?

Note that Python's log function calculates the natural log of a number.

How do you find the log value in Python?

The math. log() method returns the natural logarithm of a number, or the logarithm of number to base.

How do you take log2 in Python?

The math. log2() method returns the base-2 logarithm of a number.


1 Answers

One other thing you might want to consider is using the Taylor series of the natural logarithm:

enter image description hereenter image description here

Once you've approximated the natural log using a number of terms from this series, it is easy to change base:

enter image description here


EDIT: Here's another useful identity:

enter image description here

Using this, we could write something along the lines of

def ln(x):
    n = 1000.0
    return n * ((x ** (1/n)) - 1)

Testing it out, we have:

print ln(math.e), math.log(math.e)
print ln(0.5), math.log(0.5)
print ln(100.0), math.log(100.0)

Output:

1.00050016671 1.0
-0.692907009547 -0.69314718056
4.6157902784 4.60517018599

This shows our value compared to the math.log value (separated by a space) and, as you can see, we're pretty accurate. You'll probably start to lose some accuracy as you get very large (e.g. ln(10000) will be about 0.4 greater than it should), but you can always increase n if you need to.

like image 86
arshajii Avatar answered Oct 27 '22 18:10

arshajii