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!
Note that Python's log function calculates the natural log of a number.
The math. log() method returns the natural logarithm of a number, or the logarithm of number to base.
The math. log2() method returns the base-2 logarithm of a number.
One other thing you might want to consider is using the Taylor series of the natural logarithm:
Once you've approximated the natural log using a number of terms from this series, it is easy to change base:
EDIT: Here's another useful identity:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With