Gammer
Gammer

Reputation: 5628

Python 3x : Importing Math library python

I have the following code which i want to execute :

import math

class A(object): 

    def someNum(self, num): 
        num = int(math.log2(num))
        return num

a = A()
a.someNum('9')

But it throws an exception :

Traceback (most recent call last):
  File "main.py", line 34, in <module>
    a.numToLoc('9')
  File "main.py", line 30, in numToLoc
    num = int(math.log2(num))
AttributeError: 'module' object has no attribute 'log2'

What am i missing ?

Upvotes: 1

Views: 3962

Answers (3)

user3064538
user3064538

Reputation:

You have a file called math.py in the same directory as the code you're trying to run. Delete or rename it.

When you import math, Python walks through the directories in sys.path and imports the first file called math.py (or a directory called math with an __init__.py file inside) that it sees. The first entry in sys.path is the current directory, so it sees your math.py first.

See the documentation for modules or for the import statement.

Upvotes: 0

Sreeragh A R
Sreeragh A R

Reputation: 3021

As already suggested either use Python3.3 or above or use math.log(num, 2)

Another slight modification is required.

Please change

a.someNum('9')

to

a.someNum(9)

Else this error occurs.

TypeError: a float is required

Upvotes: -1

H. Gourl&#233;
H. Gourl&#233;

Reputation: 894

math.log2 was introduced in Python 3.3. You are probably using an earlier version.

In those earlier versions, you can use

math.log(num, 2)

instead.

Upvotes: 5

Related Questions