Calculating Logarithms with Python

我怕爱的太早我们不能终老 提交于 2020-01-11 12:08:37

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!