-2

I have this code:

import math

n2 = [0,1,2,3]
for i in range(1,3):
  x = math.log2(n2[i])
n2 += x
print(n2)

When I try it, I get: ValueError: math domain error. Why? What is wrong, and how do I fix it?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
susmit410
  • 9
  • 4
  • 1
    Are you sure? this code should raise another exception (*float is not iterable*) – DeepSpace Feb 02 '19 at 17:12
  • 3
    To help improve the information provided in your question for the next time, it would help to provide the expected output you are looking for in order to fully understand what your end goal is with your code. Also, as noted already, your code is producing a different exception. Please ensure that next time that the error and code match each other. – idjaw Feb 02 '19 at 17:17

2 Answers2

0

This code, as posted, raise another error: TypeError: 'float' object is not iterable.

However, the error you say that you get is reproduced by this code:

import math

n2 = [0, 1, 2, 3]
for i in n2:
    x = math.log2(i)

You are attempting to call math.log2 with 0 which makes no sense. As the error says, 0 is not in the domain of any of the log functions. There is no such x that satisfies kx= 0 for any k.

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
-1

You define n2 as a list. But near the end you try to execute

n2 += x

You are trying to add the float value x to the list n2. This causes the error

'float' object is not iterable

Note that is not the error you state in your question. The error you state is the result if you change the range(1,3) to range(3) or range(0, 3). That attempts to take the logarithm of the first element in your array, namely zero, and that does not have a logarithm.

You probably want to indent that next-to-last line and change it to

n2 += [x]

That has the printout

[0, 1, 2, 3, 0.0, 1.0]
Rory Daulton
  • 21,934
  • 6
  • 42
  • 50