使用日志时python中的数学域错误 [英] Math domain error in python when using log

查看:114
本文介绍了使用日志时python中的数学域错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在写的东西:

>>> import math
>>> 2/3*math.log(2/3,2)

这是我遇到的错误:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: math domain error

有人可以解释我在做什么错吗? 谢谢.

Can someone please explain what I'm doing wrong? Thanks.

推荐答案

我假设这是Python 2.7.

I'm assuming this is Python 2.7.

在2.7中,因为默认情况下为分隔楼层,所以2/3的值为0.因此,您尝试的是日志0,因此会出现错误.另一方面,Python 3默认情况下会进行浮点除法.

In 2.7, 2/3 evaluates to 0 since division floors by default. Therefore you're attempting a log 0, hence the error. Python 3 on the other hand does floating point division by default.

要获得正确的行为,您可以:

To get the correct behaviour you can either:

  1. from __future__ import division,可为您提供Python 2.7中的Python 3划分行为.
  2. 将每个2/3替换为2/float(3)2/3.0.
  1. from __future__ import division, which gives you Python 3 division behaviour in Python 2.7.
  2. Replace each 2/3 with 2/float(3), or 2/3.0.

这篇关于使用日志时python中的数学域错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆