-1

As you can see from watch, l[u][0] must be 0.5, but it returns 0

u = 0
for j in range(n):
    if k == j:
        continue
    l[u][0] = -x[j] / (x[k] - x[j])
    l[u][1] = 1 / (x[k] - x[j])
    u = u + 1

screenshot

What's wrong with it?

Bruno Gelb
  • 5,322
  • 8
  • 35
  • 50
user3528837
  • 65
  • 1
  • 2
  • 10
  • 4
    Integer division. ALso, please take the time to type (or copy) that code into your question, instead of linking some image with the code inside. – tobias_k Apr 16 '14 at 21:54
  • 2
    Worth noting that, on python3 however `1/2` gives `0.5` by default without explicit casting – shaktimaan Apr 16 '14 at 21:57

1 Answers1

4

The division is not "wrong". It is integer division (a.k.a. floor division).

When you divide two integers, the result is an integer:

>>> 3/4
0
>>> 4/4
1

When you divide two floating-point numbers (numbers with a fractional part), the result is a float:

>>> 3./4
0.75
>>> 4./4
1.0

Note that this "problem" is confined to Python 2. One of the changes in Python 3 is to make normal division coerce to floats:

>>> 3/4   # Python 3 behavior
0.75

and to require a second operator (also in Python >2.2) to achieve integer division:

>>> 3//4
0
Two-Bit Alchemist
  • 17,966
  • 6
  • 47
  • 82