Question

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?

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top