问题
I am trying to calculate logarithms using the math module of python (math.log(x,[base])
, however when I use float(raw_input)
for the x and base values, it gives me the error, ZeroDivisionError: float division by zero
.
x = 9.0
base = 3.0
回答1:
Nonsense, it works perfectly well
>>> import math
>>> x=float(raw_input())
9.0
>>> base=float(raw_input())
3.0
>>> math.log(x, base)
2.0
Why don't you show us exactly how you reproduce the problem? wim is quite correct - a base of 1
will give that error
>>> base=float(raw_input())
1.0
>>> math.log(x, base)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: float division by zero
On the otherhand - if x<=0
you get a "math domain error"
>>> x=float(raw_input())
0
>>> math.log(x, base)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: math domain error
回答2:
You should avoid x<=0 as it is not defined !
来源:https://stackoverflow.com/questions/9883317/calculating-logarithms-with-python