capcloudcoder
capcloudcoder

Reputation: 19

Python math.log function math domain error

Using the code below:

import math
-2/3*math.log(2/3,2)-1/3*math.log(1/3,2)

Gives:

ValueErrorTraceback (most recent call last) in () 1 import math ----> 2 -2/3*math.log(2/3,2)-1/3*math.log(1/3,2)

ValueError: math domain error

Where as :

import math
-.66*math.log(.66,2)-1/3*math.log(.33,2)

Works.

What is wrong with the first code?

Upvotes: 1

Views: 162

Answers (2)

Mureinik
Mureinik

Reputation: 311468

I'm guessing this is Python 2, right?

In Python 2, the / operator between two integers performs integer division, leaving only the part to the left of the decimal point. So, in Python 2, your expression would evaluate as:

-1*math.log(1,2)-1/3*math.log(02)

From here, it's easy to see why you get the error.

One alternative is to import the __future__ division operator which would act like you expect:

from __future__ import division

Upvotes: 1

Amadan
Amadan

Reputation: 198334

That will only happen in Python 2, where / is an integral division operator when between integers: 1/3 results in 0 — and it is not possible to use math.log on zero.

In Python 3, / is always a floating point division operator: 1/3 is 0.3333333333333333. (Integral division was moved to //.) Thus, the posted code would not result in an error in Python 3.

Upvotes: 0

Related Questions