Python Logarithm, Value Error : math domain error

2583 views python
2

I am learning math with python, when I tried this code for logarithm it give me this error, any help ?

import math
n = 1000000
n2 = 0
for i in range(n):
    x = math.log2(i)
    n2 += x
print(n2)

it give me a value error : "ValueError: math domain error"

answered question

You are calculating log2(0), which is - inf. Hence you are getting the error. Try range(1,n).

3 Answers

11

The range(n) is from 0 to n-1 But Log(0) is not defined hence use range(1,n) instead.

posted this
5

You are calculating log2(0), which is - inf. Hence you are getting the error. Try range(1,n).

posted this
6

import math
n = 1000000
n2 = 0
for i in range(1,n):
    x = math.log2(i)
    n2 += x
print(n2)

happy codeing !

posted this

Have an answer?

JD

Please login first before posting an answer.